1, inheritance
In Java, a class can be inherited through the extends keyword, and implements can inherit multiple interfaces. Inheritance allows classes that create hierarchical hierarchies.
The inheritance mechanism improves the reusability of the code, so that the relationship between the class and the class, with this relationship, has the characteristics of polymorphism.
Note: Java supports single inheritance, but it can inherit multiple layers.
Subclasses can have non-private methods and properties of the parent class that can inherit methods from the parent class, override the methods of the parent class, and extend the parent.
Increases the connection between classes, i.e. increases the coupling.
The General format is:
Class Parent class { }
Class Subclass extends parent class { }
Demo1:
1 PackageCom.hpioneer.Demo;2 3 Public classTest_extends {4 Public Static voidMain (string[] args) {5Zi z =NewZi ();6 //z.show ();7 }8 }9 classFu {Ten Static { OneSystem.out.println ("Static code block FU"); A } - - { theSystem.out.println ("Construct code block FU"); - } - - PublicFu () { +System.out.println ("Construction Method Fu"); - } + } A at classZiextendsFu { - Static { -System.out.println ("Static code block Zi"); - } - - { inSystem.out.println ("Construct code block Zi"); - } to + PublicZi () { -System.out.println ("Construction Method Zi"); the } *}
Demo2:
< Span class= "Hl-code" > < The span class= "hl-brackets" >super keyword can be used to implement access to a parent class member to refer to the parent class of the current object. The This keyword is used to point to yourself.
Super can call the constructor of the parent class, the method (the same as the subclass, is overridden)
1 classAnimal {2 voideat () {3System.out.println ("Animal:eat");4 }5 }6 7 classDogextendsAnimal {8 voideat () {9System.out.println ("Dog:eat");Ten } One voideattest () { A This. Eat ();//This invokes its own method - Super. Eat ();//Super calls the parent class method - } the } - - Public classTest { - Public Static voidMain (string[] args) { +Animal A =NewAnimal (); - a.eat (); +Dog d =NewDog (); A d.eattest (); at } -}
2, overload (override) and override (overload)
Overrides are rewritten on the implementation of the methods allowed by the parent class, and the return values and parameters cannot be changed.
Overloading is a class in which the method name is the same, the parameter is different, and the return value type can be different.
Java object-oriented, inheritance, polymorphic