- 类作为形参和返回值
- 抽象类作为形参和返回值
- 接口作为形参和返回值
类作为形参时,传入的需耀世类的对象;类作为返回类型时,返回的也是类的对象
定义一个 Cat 类:
public class Cat { public void eat() { System.out.println("Cat is eating"); } }
定义测试类:
public class Demo { public static void main(String[] args) { // 实际传入 Cat 类的对象 animalEat(new Cat()); Cat cat = getCat(); cat.eat(); } // 方法形参为 Cat 类 public static void animalEat(Cat cat) { cat.eat(); } // 返回类型为 Cat 类型,实际返回 Cat 类的对象 public static Cat getCat() { Cat cat = new Cat(); return cat; } }
输出:
Cat is eating Cat is eating抽象类作为形参和返回值
抽象类作为方法形参时,由于抽象类不能实例化,因此需要利用多态创建该抽象类的子类对象,将其子类对象作为参数传入方法;当以抽象类作为方法的返回类型时,实际返回的也是其子类对象
来看案例,对于抽象类 Animal:
public abstract class Animal { private int age; public abstract void eat(); }
创建两个子类 Cat 和 Dog:
public class Cat extends Animal{ @Override public void eat() { System.out.println("Cat is eating"); } }
public class Dog extends Animal { @Override public void eat() { System.out.println("Dog is eating"); }
在测试类中定义一个以抽象类 Animal 为形参的方法以及一个以 Animal 类作作为返回类型的方法:
public static void animalEat(Animal a) { a.eat(); } public static Animal getAnimal() { Animal a = new Cat(); // Cat a = new Cat(); 也可以这样写 return a; }
测试代码:
public static void main(String[] args) { Animal ani = new Cat(); animalEat(ani); Cat cat = new Cat(); animalEat(cat); animalEat(new Cat()); animalEat(new Dog()); Animal a = getAnimal(); a.eat(); }
运行结果:
Cat is eating Cat is eating Cat is eating Dog is eating Cat is eating接口作为形参和返回值
类似于抽象类,接口也不能实例化,所以接口作为形参和返回值时传入的和接受的都是实现该接口的类的对象
定义接口 Climb 以及 Cat 类实现该接口:
public interface Climb { void climbing(); }
public class Cat implements Climb { public void climbing() { System.out.println("The cat can now climb"); } }
测试代码:
public class Demo { public static void main(String[] args) { Climb c = new Cat(); catClimb(c); Cat cat = new Cat(); catClimb(cat); catClimb(new Cat()); Climb a = getClimbingAnimal(); a.climbing(); } public static void catClimb(Climb c) { c.climbing();; } public static Climb getClimbingAnimal() { // Climb c = new Cat(); 这样写也可以 Cat c = new Cat(); return c; } }
运行结果:
The cat can now climb The cat can now climb The cat can now climb The cat can now climb