Inheritance rules in Java:
1. Subclasses inherit all member variables and member methods of the parent class, but cannot inherit the parent class's constructor method.
2. Subclasses inherit the member variables of the parent class, but the subclass cannot directly access the private variables of the parent class, which can be accessed through the Getter/setter () method
3. Child class call rules for parent class constructors:
A. The constructor method of a subclass must first call the parent class's constructor method.
B. If no display is specified, the constructor method of the subclass calls the parameterless constructor method in the parent class by default.
1 Public classAnimal {2 PublicAnimal () {3System.out.println ("This was a constructor for Animal");4 }5 }6 7 Public classDogextendsAnimal {8 PrivateString name;9 Ten PublicDog () { OneSystem.out.println ("This was a constructor for Dog"); A } - - PublicDog (String name) { the This. Name =name; -System.out.println ("This was a constructor for" + This. Name); - } - } + - Public classTest { + Public Static voidMain (String args[]) { ADog D1 =NewDog (); at -Dog D2 =NewDog ("Big Yellow"); - } -}
Last Run Result:
Indicates that the subclass does not display a call to the parent class construction method, but the parent class's parameterless constructor method is called by default.
C. If there is no parameterless construction method in the parent class, the compilation will fail. Make a slight change to the above procedure:
Public classAnimal { PublicAnimal (String s) {System.out.println ("This was a constructor for Animal"); }} Public classDogextendsAnimal {PrivateString name; PublicDog () {System.out.println ("This was a constructor for Dog"); } PublicDog (String name) { This. Name =name; System.out.println ("This was a constructor for" + This. Name); }}
An error occurs when you change the parameterless construction method in the parent class animal to a constructor with parameters.
D. If there are multiple construction methods in the parent class, you can use super (the argument list) to invoke the parent class construction method.
For example, the constructor method in the above subclass is explicitly added as the parent class has the parameter construction method, the program compiles through.
Public classAnimal { PublicAnimal (String s) {System.out.println ("This was a constructor for Animal"); }} Public classDogextendsAnimal {PrivateString name; PublicDog () {Super("AAA"); System.out.println ("This was a constructor for Dog"); } PublicDog (String name) {Super("BBB"); This. Name =name; System.out.println ("This was a constructor for" + This. Name); }}View Code
Anyway, the subclass must first call the parent class's construction method, remember ~ ~
Java Object-oriented inheritance