class Grandparent { public Grandparent() { System.out.println("GrandParent Created."); } public Grandparent(String string) { System.out.println("GrandParent Created.String:" + string); } } class Parent extends Grandparent { public Parent() { System.out.println("Parent Created"); super("Hello.Grandparent."); } } class Child extends Parent { public Child() { System.out.println("Child Created"); } } public class Test{ public static void main(String args[]) { Child c = new Child(); } }
不能经过编译,构造函数调用必须是构造函数中的第一个语句。java
class Parent extends Grandparent { public Parent() { super("Hello.Grandparent."); System.out.println("Parent Created"); } }
运行结果为:编程
GrandParent Created.String:Hello.Grandparent. Parent Created Child Created`
子类的构造方法必须先调用父类构造,再执行子类构造方法。eclipse
class Animal{ void shout(){ System.out.println("动物叫!"); } } class Dog extends Animal{ public void shout(){ System.out.println("汪汪......!"); } public void sleep() { System.out.println("狗狗睡觉......"); } } public class Test{ public static void main(String args[]) { Animal animal = new Dog(); animal.shout(); animal.sleep(); Dog dog = animal; dog.sleep(); Animal animal2 = new Animal(); dog = (Dog)animal2; dog.shout(); } }
1.sleep()使用方法是在子类中新定义的,sleep中没有考虑到父类,应该在父类中覆写,不能够直接使用子类的方法。
2.将(Dog)animal将父类转为子类便可。
更改:函数
class Animal{ void shout(){ System.out.println("动物叫!"); } void sleep(){ System.out.println("动物睡觉!"); } } class Dog extends Animal{ public void shout(){ System.out.println("汪汪......!"); } public void sleep() { System.out.println("狗狗睡觉......"); } } public class Test{ public static void main(String args[]) { Animal animal = new Dog(); animal.shout(); animal.sleep(); Dog dog = (Dog)animal; dog.sleep(); Animal animal2 = new Dog(); dog = (Dog)animal2; dog.shout(); } }
运行结果:学习
汪汪......! 狗狗睡觉...... 狗狗睡觉...... 汪汪......!
class Person { private String name ; private int age ; public Person(String name,int age){ this.name = name ; this.age = age ; } } public class Test{ public static void main(String args[]){ Person per = new Person("张三",20) ; System.out.println(per); System.out.println(per.toString()) ; } }
(1)程序的运行结果以下,说明什么问题?测试
Person@166afb3 Person@166afb3
在Person类中没有定义方法toString(),最后定不定义结果同样。this
(2)那么,程序的运行结果究竟是什么呢?利用eclipse打开println(per)方法的源码,查看该方法中又调用了哪些方法,可否解释本例的运行结果?设计
public void println(Object x) { String s = String.valueOf(x); synchronized (this) { print(s); newLine(); } }
(3)在Person类中增长以下方法code
public String toString(){ return "姓名:" + this.name + ",年龄:" + this.age ; }
从新运行程序,程序的执行结果是什么?说明什么问题?
运行结果:
姓名:张三,年龄:20
姓名:张三,年龄:20
父类中的toString()方法覆盖了子类中的方法。对象
实验内容:
程序设计思路:设计一个员工类,一个管理员类,一个职工类,一个测试类。管理员类和职工类分别继承员工类。