类名作为形参和返回值
方法的形参是类名,其实需要的是方法的对象
方法的返回值是类名,其实返回的是该类的对象
public class cat {
public void eat(){
System.out.println("猫吃鱼");
}
}
public class catoperate {
public void eatoperate(cat c){//方法的形参是类名
c.eat();
}
//带返回值的
public cat getCat(){
cat c = new cat();
return c;//返回一个cat类型的对象
}
}
public class catdemon {
public static void main(String[] args){
catoperate a = new catoperate();//创建操作类的对象
cat c = new cat();//因为eatoperate是带参的方法,需要创建一个对象,然后放到括号里面
a.eatoperate(c);
cat c2 = a.getCat();//等价于cat c2 = new cat();
c2.eat();
}
}
抽象类名作为形参和返回值
利用多态
public class cat extends animal {
@Override
public void eat() {
System.out.println("猫吃鱼");
}
}
public abstract class animal {
public abstract void eat();
}
public class animaloperate {
public void eatoperate(animal c){
c.eat();
}
public animal eat(){
animal a = new cat();
return a;
}
}
public class test {
public static void main(String[] args){
animaloperate a = new animaloperate();//创建操作类对象
animal c = new cat();//创建形参对象
a.eatoperate(c);
animal b = a.eat();//等同于new cat(); 相当于猫类的对象
b.eat();
}
}
接口作为形参和返回值
注意接口和抽象类都不能实例化,都需要通过多态来创建对象