类作为参数时
类:在调用方法时,传入相应类的对象(匿名类)
package org.wdzl.unit04;
/**
* 形式参数是引用数据类型问题
* 1、类:在调用方法时,传入相应类的对象(匿名类)
* 2、抽象类
* 3、接口
*/
public class ArgsDemo {
public static void main(String[] args) {
StudentDemo studentDemo = new StudentDemo();
//第一种创建对象
Student student = new Student();
studentDemo.function(student);
//第二中匿名对象
studentDemo.function(new Student());
}
}
class Student{
public void study(){
System.out.println("Good Study!!!");
}
}
class StudentDemo{
public void function(Student student){
student.study();
}
}
抽象类作为参数时
抽象类:在调用方法时,传入抽象类子类对象。
package org.wdzl.unit04;
/**
* 形式参数是引用数据类型问题
* 1、类:在调用方法时,传入相应类的对象(匿名类)
* 2、抽象类:在调用方法时,传入抽象类子类对象。
* 3、接口
*/
public class ArgsDemo1 {
public static void main(String[] args) {
PersonDemo personDemo = new PersonDemo();
//personDemo.function();//编译时异常
//抽象类不能被实例化对象,其次抽象类中的方法也没有方法体,即便可以调用也没有任何意义。
Person person = new Student1();
personDemo.function(person);
}
}
abstract class Person{
public abstract void study();
}
class PersonDemo{
public void function(Person person){//Person p = new Student1();
person.study();
}
}
class Student1 extends Person{
@Override
public void study() {
System.out.println("Good Study!!!");
}
}
接口作为参数时
接口:在调用方法时,传入实现类的对象。
package org.wdzl.unit04;
/**
* 形式参数是引用数据类型问题
* 1、类:在调用方法时,传入相应类的对象(匿名类)
* 2、抽象类:在调用方法时,传入抽象类子类对象。
* 3、接口:在调用方法时,传入实现类的对象。
*/
public class ArgsDemo3 {
public static void main(String[] args) {
Teacher teacher = new Teacher();
// teacher.method();//因为接口中的方法都是抽象方法,即使调用了也没有任何意义
ExtendMethod extendMethod = new TeacherDemo();
teacher.method(extendMethod);
}
}
interface ExtendMethod{
public abstract void cook();
}
class TeacherDemo implements ExtendMethod{
@Override
public void cook() {
System.out.println("做饭");
}
}
class Teacher {
public void method(ExtendMethod extendMethod){//ExtendMethod e = new Teacher();
extendMethod.cook();
}
}