這可以幫助你瞭解更多關於繼承和超()...
的源代碼:
$ cat Inheritance.java
class ParentClass {
private String privateParentProperty;
public ParentClass() {
this.privateParentProperty = "Hi, this is ParentClass, my instance came from " + String.valueOf(this.getClass()) + "!";
}
public String getPrivateParentProperty() {
return this.privateParentProperty;
}
}
class ChildClass extends ParentClass {
private String childProperty;
public ChildClass() {
super(); // I can explictly call the parent constructor in a child class by calling super in the first line of the child class...
this.childProperty = "Hi, I came from " + String.valueOf(this.getClass()) + "!";
}
public String getChildProperty() {
return this.childProperty;
}
@Override
public String getPrivateParentProperty() {
String parentProperty = super.getPrivateParentProperty(); // I can override a parent method in a child class and call that method from the parent in the first line of the child's class.
parentProperty += " I, " + String.valueOf(this.getClass()) + " am intercepting this call and adding my own message to my parent."; // Note: I am not modifying the private property from the parent, but rather appending to a new String local to this method.
return parentProperty;
}
}
class MainApp {
public static void main(final String[] args) {
ParentClass parentClassInstance = new ParentClass();
System.out.println (parentClassInstance.getPrivateParentProperty());
ChildClass childClassInstance = new ChildClass();
System.out.println(childClassInstance.getChildProperty());
System.out.println(((ParentClass)childClassInstance).getPrivateParentProperty()); // I can cast a child to its parent class and invoke the method... however, because the child overrode the method and the instance is the child instance, even with the cast, the method from the child will execute.
System.out.println(childClassInstance.getPrivateParentProperty()); // I can also call this method directly from the childwithout needing to cast, because it inherits it from the parent.
}
}
編譯和測試輸出:
$ javac Inheritance.java
$ java MainApp
Hi, this is ParentClass, my instance came from class ParentClass!
Hi, I came from class ChildClass!
Hi, this is ParentClass, my instance came from class ChildClass! I, class ChildClass am intercepting this call and adding my own message to my parent.
Hi, this is ParentClass, my instance came from class ChildClass! I, class ChildClass am intercepting this call and adding my own message to my parent.
希望這有助於!
非常感謝,我沒有想到這麼簡單。 – AnKo