Java object-oriented -001-inheritance

Source: Internet
Author: User

The concept of inheritance

Inheritance is the child class inherits the characteristics and behavior of the parent class , so that the subclass object (instance) has the parent class's instance domain and method, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class.

The Inheritance in life

Rabbits and sheep belong to herbivores, and lions and leopards belong to carnivores.

Herbivores and carnivores belong to animals.

So the relationship that the inheritance needs to conform to is: Is-a, the parent class is more generic, the subclass is more specific.

Although herbivores and carnivores belong to animals, there are differences in their properties and behavior, so subclasses have their own characteristics as well as the general nature of the parent class.

The inheritance format of the ① class can be declared by the extends keyword

The extends keyword can be used to declare that a class inherits from another class.

// the inheritance format of the class /* Class Parent Class {}class Child class extends parent class {} */

Why ② need to inherit

Next we illustrate this requirement by example.

The development of animal species, in which animals are penguins and mice, are required as follows:

Penguin: Attribute (name, id), method (eat, sleep, introduce yourself)

Mouse: Attribute (name, id), method (eat, sleep, introduce yourself)

//Penguin Class Public classPenguin {PrivateString name; Private intID;  PublicPenguin (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 +". "); }}
//Mouse Type Public classMouse {PrivateString name; Private intID;  PublicMouse (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 +". "); }}

From the two code can be seen, the code is duplicated , leading to the result is a large and bloated code , and maintenance is not high (maintainability is mainly in the late need to modify the time, you need to modify a lot of code, error-prone),

So to fundamentally solve the problem of these two pieces of code, you need to inherit, the same part of the two code is extracted to form a parent class :

//Animal Class (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 +". "); }}

This animal class can be used as a parent class, and then the Penguin class and the mouse class inherit this class, there is the parent class in the properties and methods, the subclass will not have duplicate code, maintenance is also improved, the code is more concise, improve the reusability of code (reusability is mainly can be used multiple times, You don't have to write the same code more than once to inherit the code :

//Penguin Category: Public classPenguinextendsAnimal { PublicPenguin (String MyName,intmyID) {        Super(MyName, myID); }}//Mouse Type: Public classMouseextendsAnimal { PublicMouse (String MyName,intmyID) {        Super(MyName, myID); }}

Features of ③ inheritance

 ///////D.java inheritance is single inheritance, but can be multiple inheritance,//   // E. Improved coupling between classes (disadvantages of inheritance, high coupling will result in a link between the code).   

④ Inheritance keyword

Inheritance can use the two keywords extends and implements to implement inheritance, and all classes inherit from Java.lang.Object,

When a class does not inherit two keywords, the default inherits the object (this class is in the Java.lang package, so the import is not required) ancestor class.

1.extends keywords

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.

//Animal Class (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 classPenguinextendsanimal{}

2.implements keywords

The use of 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).

 Public Interface A {    publicvoid  eat ();      Public void sleep ();}  Public Interface B {    publicvoid  Show ();}  Public class Implements A, b {    }

3.super and the This keyword

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.

classAnimal {voideat () {System.out.println ("Animal:eat"); }}classDogextendsAnimal {voideat () {System.out.println ("Dog:eat"); }    voideattest () { This. Eat ();//This invokes its own method        Super. Eat ();//Super calls the parent class method    }} Public classTest { Public Static voidMain (string[] args) {Animal a=NewAnimal ();        A.eat (); Dog D=NewDog ();    D.eattest (); }}//Output Result://animal:eat//dog:eat//animal:eat

4.final keywords

The final keyword declares that 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:

// a declaration class: // Final Class class name {// class Body} // B declaration method: // modifier (public/private/default/protected) Final return value type method name () {// method Body} // Note: Instance variables can also be defined as final, and variables defined as final cannot be modified. A method declared as a final class is automatically declared final, but the instance variable is not final

④ Constructors

A subclass cannot inherit the constructor (constructor or constructor) of the parent class, and if the constructor of the parent class has parameters, the constructor of the parent class must be explicitly called through the Super keyword in the constructor of the child class with the appropriate argument list.

if the parent class constructor has no parameters, the parent class constructor is called automatically by the system without the Super keyword being called in the constructor of the child class .

classSuperclass {Private intN; Superclass () {System.out.println ("Superclass ()"); } Superclass (intN) {System.out.println ("Superclass (int n)");  This. N =N; }}classSubclassextendssuperclass{Private intN; Subclass () {Super(300); System.out.println ("Subclass"); }     PublicSubclass (intN) {System.out.println ("Subclass (int N):" +N);  This. N =N; }} Public classtestsupersub{ Public Static voidMain (String args[]) {Subclass SC=Newsubclass (); Subclass SC2=NewSubclass (200); }}//the output is://superclass (int n)//Subclass//Superclass ()//Subclass (int n):

Java object-oriented -001-inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.