Inherited
If some classes contain the same code, you can extract the same code into a new class, and then use the extends keyword to bring the original class and the new class into relationship---inheritance.
By inheritance, the original class is called the subclass (derived class), and the new class becomes the parent class (superclass/base class).
Subclasses can use a subset of the methods and properties in the parent class by inheriting the parent class
Note: Subclasses inherit all data fields (method + properties) of the parent class, but only a subset of the data fields are visible to the child class after inheritance
In Java, a subclass of single inheritance between classes and classes can inherit only one parent class, but a parent class can have multiple subclasses
The inheritance format of the class
In Java, the extends keyword can be used to declare that a class is inherited from another class in the following general form:
class classextends parent class {}
Instance:
Parent class:
Public classAnimal {PrivateString name; Private intID; PublicAnimal (String MyName,intmyID) {Name=MyName; ID=myID; } Public voideat () {System.out.println (name+ "eating"); } Public voidsleep () {System.out.println (name+ "Sleeping"); } Public voidIntroduction () {SYSTEM.OUT.PRINTLN ("Hello, everyone!" I am "+ ID +" Number "+ Name +". "); } }
Penguin Category:
Public class extends Animal { publicint myid) { super(MyName, myID);} }
Mouse Type:
Public class extends Animal { publicint myid) { super(MyName, myID); } }
Inherited attributes
-
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).
Inheritance in Java