Inherited
Subclasses have properties that are not private to the parent class, methods.
Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
Subclasses can implement methods of the parent class in their own way.
Java inheritance is a single inheritance, but can be multiple inheritance, single inheritance is a subclass can inherit only one parent class, multiple inheritance is, for example, Class A inherits Class B, Class B inherits Class C, so the Class C is the parent class of Class B, and Class B is the parent class of Class A, which is a feature that differs from C + + inheritance.
Increases the coupling between classes (the disadvantage of inheritance, high coupling will cause the relationship between the code).
extends keyword: in Java, the inheritance of a class is a single inheritance, that is, a subclass can only have one parent class, so extends can inherit only one class.
1 Public classAnimal {2 PrivateString name; 3 Private intID;4 PublicAnimal (String myName, String myID) {5 //Initializing property values6 } 7 Public voidEat () {//the specific implementation of the eating method}8 Public voidSleep () {//the specific implementation of the Sleep method}9 } Ten One Public classPenguinextendsanimal{ A}
implements Keywords: using the Implements keyword can be disguised to make Java has multiple inheritance, using the scope of the class to inherit the interface, you can inherit multiple interfaces (interfaces and interfaces separated by commas).
1 Public InterfaceA {2 Public voideat ();3 Public voidsleep ();4 }5 6 Public InterfaceB {7 Public voidShow ();8 }9 Ten Public classCImplementsA, b { One}
Super Keyword: we can use the Super keyword to implement access to a parent class member to refer to the parent class of the current object.
This keyword: point to your own reference.
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 Animal =NewAnimal (); - animal.eat (); +System.out.println ("---------------"); ADog dog =NewDog (); at dog.eat (); -System.out.println ("---------------"); - dog.eattest (); - } -}
Run output:
animal eat---------------dog eat---------------dog Eatanimal eat
Final keyword: declaring a class can define a class as not inheritable, that is, a final class, or for a decorated method that cannot be overridden by a quilt class:
Declaration method:
Modifier (Public/private/default/protectedfinal return value type method name () {// method Body}
Java Learning Note (eight): Inheritance