欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

动物类及动物的部分行为(体现封装,继承和多态)

程序员文章站 2022-04-15 17:51:43
class Animal {public static void main(String[] args) {/*Animal c1 = new Cat();c1.setName("加菲猫");c1.setLeg(4);System.out.println(c1.getName() + "是" + c1.getLeg() + "条腿");c1.eat();Cat c2 = (Cat)c1;c2.catchMouse();*/method(new Cat("...
class Animal { public static void main(String[] args) { /*Animal c1 =  new Cat();
		c1.setName("加菲猫");
		c1.setLeg(4);
		System.out.println(c1.getName() + "是" + c1.getLeg() + "条腿");
		c1.eat();
		Cat c2 = (Cat)c1;
		c2.catchMouse();*/ method(new Cat("加菲猫",4)); method(new Dog("宾利",4)); } public static void method(Animal a) { System.out.println(a.getName() + "是" + a.getLeg() + "条腿"); if(a instanceof Cat) { Cat c1 = (Cat)a; c1.eat(); c1.catchMouse(); /*System.out.println(c1.getName() + "是" + c1.getLeg() + "条腿");*/ }else if(a instanceof Dog) { Dog d1 = (Dog)a; d1.eat(); d1.lookHome(); } } } class Animal { private String name; private int leg; public Animal() {} public Animal(String name,int leg) { this.name = name; this.leg = leg; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setLeg(int leg) { this.leg = leg; } public int getLeg() { return leg; } public void eat() { System.out.println("动物吃饭"); } } class Cat extends Animal { public Cat() {} public Cat(String name,int leg) { super(name,leg); } public void eat() { System.out.println(getName() + "吃鱼"); } public void catchMouse() { System.out.println(getName() + "老鼠"); } } class Dog extends Animal { public Dog() {} public Dog(String name,int leg) { super(name,leg); } public void eat() { System.out.println(getName() + "吃肉"); } public void lookHome() { System.out.println(getName() + "看家"); } } 

显示结果为:
动物类及动物的部分行为(体现封装,继承和多态)

本文地址:https://blog.csdn.net/SHI_LUO_DE_YI_JI/article/details/107891997

相关标签: 基础 java