(抽象)类名作为形参和返回值

1.类作为形参:
分别建立Animal、AnimalOperator、AnimalDemo类:
Animal:

public class Animal {
    public void eat(){
        System.out.println("动物爱吃食物");
    }
}

AnimalOperator:

public class AnimalOperator {
    public void useAnimal(Animal a){
        a.eat();
    }

AnimalDemo

public class AnimalDemo {
    public static void main(String[] args) {
        AnimalOperator ao1=new AnimalOperator();
        Animal a1=new Animal();
        ao1.useAnimal(a1);
    }

}

运行结果:在这里插入图片描述
2.类作为返回值:
分别建立Animal、AnimalOperator、AnimalDemo类:
Animal:

public class Animal {
    public void eat(){
        System.out.println("动物爱吃食物");
    }
}

AnimalOperator:

public class AnimalOperator {
   
    public Animal useAnimal1() {
        Animal a1 = new Animal();
        return a1;
    }
}

AnimalDemo:

public class AnimalDemo {
    public static void main(String[] args) {      
        AnimalOperator ao2=new AnimalOperator();
        Animal a2=ao2.useAnimal1();
       a2.eat();
    }

}

运行结果:
在这里插入图片描述

3.抽象类作为形参:
Animal类:

public abstract class Animal {
    public abstract void eat();
}

AnimalOperator:

public class AnimalOperator {
    public void useAnimal(Animal a) {
        a.eat();
    }
}

Cat类继承Animal,并重写抽象类中方法:

public class Cat extends Animal{
    @Override
    public void eat() {
        System.out.println("猫爱吃鱼");
    }
}

AnimalDemo:

public class AnimalDemo {
    public static void main(String[] args) {
        AnimalOperator ao1=new AnimalOperator();
        Animal a1=new Cat();
        ao1.useAnimal(a1);
    }
}

执行结果:
在这里插入图片描述
4.抽象类作为返回值:
Animal类:

public abstract class Animal {
    public abstract void eat();
}

Dog类继承Animal并重写方法:

public class Dog extends Animal{
    @Override
    public void eat() {
        System.out.println("够爱吃骨头");
    }
}

AnimalOperator类:

public class AnimalOperator {
    public Animal useAnimal(){
        Animal a1=new Dog();
        return a1;
    }
}

AnimalDemo类:

public class AnimalDemo {
    public static void main(String[] args) {
        AnimalOperator ao1=new AnimalOperator();
       Animal d1=ao1.useAnimal();
        d1.eat();
    }
}

运行结果:
在这里插入图片描述

你可能感兴趣的:(java)