Java Object-oriented (two, encapsulation)

Source: Internet
Author: User
Tags modifiers

The concept inheritance of Java inheritance Inheritance is a cornerstone of Java object-oriented programming technology, because it allows classes of hierarchical hierarchy to be created. 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 of life: rabbits and sheep belong to herbivores, and lions and leopards belong to carnivorous animals. 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 a class in Java through the extends keyword can be declared that a class is inherited from another class, the general form is as follows:
class classextends  parent class {} 
Why we need inheritance 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 Category: 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, resulting in the result is a large and bloated code, and maintenance is not high (maintenance is mainly the latter 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, Extract the same part of the two code to form a parent class:
Public 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, Do not write the same code more than once) after inheriting the code:,
  penguin class:  public  class  Penguin extends   animal{ public  Penguin (String myName, int   myID)    { super   (MyName, myID);  public  void   sum () { super  .eat ();         super  .sleep ();     super  .introduction (); }}
  mouse class:  public  class  Mouse extends   Animal { public  Mouse (String myName, int      myID) { super   (MyName, myID);  public  void   sum () { super  .eat ();         super  .sleep ();     super  .introduction (); }}
Test class:  Public class Test {    publicstaticvoid  main (string[] args) {        new Mouse ("Mouse", 1);        Mouse.sum ();         New Penguin ("Penguin", 1);        Penguin.sum ();    }}
Run Diagram: 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 keyword (extends) inheritance can use the extends keyword, and all classes are inherited from Java.lang.Object, and when a class does not inherit the extends keyword, it inherits the Object by default (this class is in the Java.lang package, So you don't need an import) ancestor class. 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. public class Penguin extends animal{}super and this keyword when a new object comes out, this object produces a reference to this. The This reference points to the object itself and this can only be used in non-static methods in the class. If the new object is a subclass object, then there is a super reference inside the subclass object, which points to the parent object inside the current object. So the equivalent of a program inside a this,this point to the object itself, there is a super,super point to the current object inside the parent object. The super key in inheritance is similar to this, making a hidden member variable or member method visible, or used to refer to a hidden member variable and member member method. Super Keyword: 1: The constructor (constructor) of the calling parent class cannot inherit the constructor of the parent class (constructor or constructor), but the constructor of the parent class has parameters, and 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 and " Super (parameter list) "This statement can only be used to construct the first row of the method body in a subclass。 If the parent class has a parameterless constructor, it is not necessary to call the parent class constructor with super in the constructor of the subclass, and if the Super keyword is not used, the system automatically calls the parent class's parameterless constructor.
Super ();                     // calling the parent class without a parameter constructor Super ("Parameters")             // calling the parent class has a parameter       constructor
2: References to properties and methods of the parent class because inherited properties and methods are hidden by default, you need to use the Super keyword to invoke properties and methods that inherit from the parent class, and reference both must be placed in the method body of the subclass method
Super. Attribute name                              // Reference subclass inherited property Super. Method name (parameter list)            //  Methods that refer to subclasses that have been inherited
This keyword: point to your own reference. (This is a pointer to the object itself). For more detailed information, see the following blog: http://lavasoft.blog.51cto.com/62575/18886/about subclasses that cannot inherit from elements of the parent Class 1: Constructor 2 of the parent class: The property and method aspects of the parent class are related to their modifiers, Consistent with access modifiers.

Java Object-oriented (two, encapsulation)

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.