Perosn父类
1 package day1_26; 2 3 public class Person { 4 String name; 5 int age; 6 public void eat() { 7 System.out.println("人,吃东西"); 8 } 9 10 public void walk() { 11 System.out.println("人,走路"); 12 } 13 }
Man子类
1 package day1_26; 2 3 public class Man extends Person { 4 @Override 5 public void eat() { 6 System.out.println("男人,多吃肉长肌肉"); 7 } 8 9 @Override 10 public void walk() { 11 System.out.println("男人,霸气走路"); 12 } 13 public void earnMoney() { 14 System.out.println("男人赚钱"); 15 } 16 }
PersonTest测试类
1 package day1_26; 2 3 /** 4 * 多态是父类引用指向子类对象 5 * 多态是对于方法而言,属性无关 6 * 编译看左边(左边是父类,编译时看父类有没有这个方法,如果没有报错) 7 * 运行看右边(右边是子类,运行时如果这个方法子类重写了父类的, 8 * 那么就调用子类那个重写的方法) 9 * 10 */ 11 12 public class PersonTest { 13 public static void main(String[] args) { 14 Person p = new Person(); 15 p.eat(); 16 p.walk(); 17 //多态 18 Person p2 = new Man(); 19 p2.eat(); 20 p2.walk(); 21 System.out.println("****************"); 22 //编译看左边,即编译时类型Person,没有earnMoney()方法,所以报错 23 //p2.earnMoney(); 24 PersonTest pt = new PersonTest(); 25 pt.helloPerson(new Man()); //Person p = new Man() 26 pt.helloPerson(new Person());//Person p = new Person() 27 28 pt.helloObject(new Man()); //Object object = new Man() 29 pt.helloObject(new Person());//Object object = new Person(); 30 31 32 } 33 34 //形参是Person对象,那么调用方法时,可以放入Person对象或者其子类的对象 35 public void helloPerson(Person p) { 36 //因为walk方法被重写了,所以调用时,运行的是重写后的那个方法 37 p.walk(); 38 } 39 40 //形参是Object对象,那么调用方法时,可以放入Object对象或者其子类的对象 41 public void helloObject(Object object) { 42 //因为Perosn和Man都没有重写Object对象的方法, 43 // 所以只能调用继承Object的方法,比如toString()。 44 //编译看左边,左边是Object,它没有eat()方法,所以报错 45 //object.eat(); 46 System.out.println(object.toString()); 47 } 48 49 50 }