加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

抽象类作为方法的参数和返回值

发布时间:2021-07-06 05:38:00 所属栏目:大数据 来源: https://blog.csdn.net/summoxj
导读:抽象类Animal: public abstract class Animal { ?? ?public abstract void eat(); } 子类Cat: public class Cat extends Animal { ?? ?@Override ?? ?public void eat() { ?? ??? ?System.out.println("猫在吃鱼"); ?? ?} } 子类Dog: public class Dog ext

抽象类Animal:

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

}


子类Cat:

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


子类Dog:

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

}


测试Test类:

/*
?* 将抽象类类型,作为方法的参数进行传递
?*/
public class Test {
?? ?public static void main(String[] args) {
?? ?//调用operatorAnimal,传递子类对象
?? ??? ?Cat c=new Cat();
?? ??? ?operatorAnimal(c);
?? ??? ?operatorAnimal(new Dog());
?? ?}
?? ?/*
?? ? * 方法operatorAnimal,参数是一个抽象类
?? ? * 调用方法,传递Animal类型对象,Animal抽象类没有对象
?? ? * 只能传递Animal的子类的对象(多态)
?? ? */
?? ?public static void operatorAnimal(Animal a){
?? ??? ?//引用变量a,调用方法eat
?? ??? ?a.eat();
?? ?}
}





(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读