Animal.java
package ithema03;
public class Animal {
public int age = 40;
public void eat() {
System.out.println("动物吃东西");
}
}
Cat.java
package ithema03;
public class Cat extends Animal{
public int age = 20;
public int weight = 10;
@Override
public void eat() {
System.out.println("猫吃鱼");
}
public void playGame() {
System.out.println("猫捉迷藏");
}
}
AnimalDemo.java
package ithema03;
public class AnimalDemo {
public static void main(String[] args) {
//有父类引用指向子类对象
//成员变量:编译看左边,执行看左边
Animal a = new Cat();
System.out.println(a.age);
// System.out.println(a.weight);
//成员方法:编译看左边,执行看右边
a.eat();
a.playGame();
}
}
Animal.java
package ithema01;
public abstract class Animal {
private String name;
private int age;
public Animal () {
}
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public abstract void eat();
}
Cat.java
package ithema01;
public class Cat extends Animal{
public Cat() {
}
public Cat(String name, int age) {
super(name, age);
}
@Override
public void eat(){
System.out.println("猫吃鱼");
}
}
Dog.java
package ithema01;
public class Dog extends Animal {
public Dog() {
}
public Dog(String name, int age) {
super(name, age);
}
@Override
public void eat(){
System.out.println("狗吃骨头");
}
}
AnimalDemo.java
package ithema01;
public class AnimalDemo {
public static void main(String[] args) {
//创建对象,按照多态的方式
Animal a = new Cat();
a.setName("加菲");
a.setAge(5);
System.out.println(a.getName()+","+a.getAge());
a.eat();
System.out.println("----------------------");
Animal a2 = new Cat("Tom",6);
System.out.println(a.getName()+","+a.getAge());
a2.eat();
System.out.println("----------------------");
//创建对象,按照多态的方式
Animal a3 = new Dog();
a3.setName("拉布拉多");
a3.setAge(7);
System.out.println(a3.getName()+","+a3.getAge());
a3.eat();
System.out.println("----------------------");
Animal a4 = new Dog("摩萨耶",4);
System.out.println(a4.getName()+","+a4.getAge());
a4.eat();
}
}
/*
加菲,5
猫吃鱼
----------------------
加菲,5
猫吃鱼
----------------------
拉布拉多,7
狗吃骨头
----------------------
摩萨耶,4
狗吃骨头
Process finished with exit code 0
*/