Java Fundamentals Review Three-----Encapsulation, inheritance, and polymorphism

Source: Internet
Author: User
Tags modifier modifiers

Objective

Reviewing the Java modifiers and the string class in the previous article, this article looks back at the three main features of Java: Encapsulation, inheritance, polymorphism.

Encapsulate what is encapsulated

In the object-oriented programming approach, encapsulation refers to a method of wrapping and hiding the implementation details of an abstract function interface.

Encapsulation can be thought of as a protective barrier against random access to code and data of that class by code defined by external classes. To access the code and data for this class, you must pass strict interface control.

The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code. Proper encapsulation can make code easier to understand and maintain, and it also enhances code security.

In simple terms, the code that is often used in Java is packaged up to form a method. For example, the entity classes we use are used to protect data using private modifier variables, and to provide getter and setter methods for invocation. This is a typical package.

code example :

    public class packagingTest {            public static void main(String[] args) {            User user=new User();      //这里会报错,因为id和name是私有的,用于保护该数据    //      user.id=10;    //      user.name="张三";            user.setId(1);            user.setName("张三");            System.out.println(user.getId());            System.out.println(user.getName());        }        }        class User{        private int id;        private String name;        public int getId() {            return id;        }        public void setId(int id) {            this.id = id;        }        public String getName() {            return name;        }        public void setName(String name) {            this.name = name;        }    }    

Operation Result:

    1    张三
Benefits of using encapsulation
    1. Good encapsulation can reduce coupling.

    2. The structure within the class can be freely modified.

    3. You can have more precise control over member variables.

    4. Hide information and implement details.

Inherit What is inherited

Inheritance is a cornerstone of Java object-oriented programming technology because it allows classes of hierarchical hierarchies 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.

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.
Why Use Inheritance

The main purpose of inheritance is to reuse code! To put it simply, the duplicate code is extracted, placed in the parent class, and then inherited by subclasses, and the subclass can also extend the parent class. So in the inheritance relationship, you can understand that the parent class is more generic and the subclass more specific.

For example, in the animal world, cats and lions belong to the cat family, and the dogs and wolves belong to the canine family. And they are all animals. The cat and the lion have a common parent cat family , the cat and the dog have a common father kind of animal . So they are in accordance with the inheritance, but they differ in behavior. Both cats and dogs eat and sleep, but cats can climb trees and dogs can't.
Here, we can use the following code to illustrate.

code example:

public class extendTest {    public static void main(String[] args) {        Cat cat=new Cat();        Dog dog=new Dog();        cat.eat();        cat.sleep("cat");        cat.climbTree();        dog.eat("dog");        dog.sleep("dog");    }}class  Animal{    public void eat(String name){        System.out.println(name+"正在吃东西...");    }    public void sleep(String name){        System.out.println(name+"正在睡觉...");    }}class Cat extends Animal{    private String name="Cat";    public void eat(){        super.eat(name);        System.out.println(name+"吃完了");    }    public void sleep(){        this.sleep(name);    }        public void sleep(String name){        System.out.println(name+"刚刚睡觉!");    }        public void climbTree(){        System.out.println(name+"正在爬树!");    }}class Dog extends Animal{    }

Operation Result:

Cat正在吃东西...Cat吃完了cat刚刚睡觉!Cat正在爬树!dog正在吃东西...dog正在睡觉...

In the code above, the parent class animal implements the eat and sleep methods, and the subclass cat and dog Use the extends keyword to inherit the parent class animal. Subclass Dog inherits the parent class animal nothing, and the subclass cat inherits not only the parent class animal, but also the Climbtree method, and overrides the Eat and sleep methods of the parent class.
In the subclass cat, there are two keywords:super and this.
The meanings of these two keywords are as follows:

    • Super Keyword: implements access to the parent class member to refer to the parent class of the current object.
    • This keyword: point to your own reference.

In the preceding code, the subclass cat uses the Super keyword to invoke the Eat method of the parent class animal , using the This keyword to invoke the Sleep method in this class.

When it comes to inheritance, you have to mention a few things: final and protected modifiers, constructors, and upward transformation!
Where the final and protected modifiers have been explained in the previous Java modifier and the String class, here is a simple description.

    • Final: The decorated class cannot be inherited.
    • Protected: The decorated class is only visible to classes and all subclasses within the same package.
Constructors

Although subclasses can inherit the properties and methods of the parent class (except for the private adornment), there is the same subclass that cannot inherit, which is the constructor ! For a constructor, it can only be called, not inherited. If the subclass wants to use the constructor of the parent class, simply call with the Super keyword.

Note: If the constructor of the parent class is modified by private, it cannot be called externally, including subclasses!

Upward transformation

Converting a subclass to a parent class is moved upward above the inheritance relationship, so it is generally called upward transformation.
In the previous example, the cat and the animal belong to the inheritance relationship, then we can make the cat as an animal is the upward transformation!
For example:

public class extendTest {    public static void main(String[] args) {        Animal animal=new Cat();        animal.eat("cat");        animal.sleep("cat");    }}class  Animal{    public void eat(String name){        System.out.println(name+"正在吃东西...");    }    public void sleep(String name){        System.out.println(name+"正在睡觉...");    }}class Cat extends Animal{private String name="Cat";    public void eat(){        super.eat(name);        System.out.println(name+"吃完了");    }    public void sleep(){        this.sleep(name);    }        public void sleep(String name){        System.out.println(name+"刚刚睡觉!");    }        public void climbTree(){        System.out.println(name+"正在爬树!");    }}

Operation Result:

cat正在吃东西...cat刚刚睡觉!

The above code completes the upward transformation, but in the upward transformation there are some drawbacks, that is, the loss of properties and methods. For example, the Climbtree () method and the Name property in the Cat class are missing from the above code. So be careful with the upward transformation!

Multiple inheritance

Java inheritance is single inheritance, but multiple inheritance can be achieved!
Although a subclass can inherit only one parent class, subclasses of subclasses may also subclass the child class.
For example, Class C inherits Class B, Class B inherits Class A, so the Class A is the parent of Class B, and Class B is the parent class of Class C.

Disadvantages of inheritance

Although inheritance greatly improves the reusability of code, it also improves the coupling between classes! Parent class changes, subclasses must change! Thus, inheritance destroys encapsulation because, for the parent class, its implementation details are transparent to the subclass.
So use inheritance with caution!!!

Polymorphic What is polymorphic

Polymorphism refers to the existence of different state of things in the course of operation.

Polymorphism refers to the specific type of reference variable defined in the program and the method calls made through the reference variable are not deterministic during programming, but are determined during the program's run.

Requirements for using polymorphism

Three prerequisites for polymorphic presence:

    1. To have an inheritance relationship;
    2. Subclasses to override the method of the parent class;
    3. The parent class reference points to the subclass object, which is the upward transformation.
A simple example of polymorphic use

In the inheritance explained above, we used the relationship between cat and animal, here we can also use this, only need to change the code slightly, you can achieve polymorphism.

code example:

public class Test {    public static void main(String[] args) {        Animal animal=new Cat();        animal.eat();    }}class  Animal{    private String name="Animal";    public void eat(){        System.out.println(name+"正在吃东西...");        sleep();    }    public void sleep(){        System.out.println(name+"正在睡觉...");    }}class Cat extends Animal{    private String name="Cat";    public void eat(String name){        System.out.println(name+"吃完了");        sleep();    }    public void sleep(){        System.out.println(name+"正在睡觉");    }}

Output Result:

Animal正在吃东西...Cat正在睡觉

After seeing the results of the operation, if you are unfamiliar with polymorphism, do you feel a little strange?
The first sentence of printing should be understood, why the second sentence of printing is not the method of animal, but the method in cat?

We know that polymorphism means that things exist in different states in the course of their operation. here, we use inheritance, rewriting, and upward transformation.
Here by the way:

In an upward transformation, a reference to a parent class can point to a multi-seed class object, and at run time it is determined by the type of the actual referenced object that is the same message.

Based on the above understanding, let's look at the example that we just had.
In the Cat class, the sleep method of the parent class animal is overridden, and the Eat method is overloaded. After overloading the Eat (String name) method and the parent class animal The Eat () method is not the same method, because it is lost in the upward transformation. The cat subclass overrides the Sleep method, so it is not lost when it is up, and because specifying a reference type to the object is cat, animal calls the Eat () method, first calling the Eat () method in this class, and then calling the sleep () method in the subclass!

Conclusion:

When a parent class reference points to a subclass method, a method that exists in the parent class must be called, and if the method is overridden in a subclass, the method in the subclass is called dynamically at run time, which is polymorphic.

Advantages of using polymorphism

Excerpt from: https://www.cnblogs.com/jack204/archive/2012/10/29/2745150.html

    1. Replaceable (substitutability). Polymorphism is replaceable for existing code. For example, polymorphism works on the Circle Circle class and works on any other circular geometry, such as a ring.
    2. Extensibility (Extensibility). Polymorphism has extensibility for code. Adding new subclasses does not affect the polymorphism, inheritance, and the operation and manipulation of other attributes of existing classes. In fact, new subclasses are more likely to get polymorphic functions. For example, it is easy to add the polymorphism of sphere class on the basis of realizing the multi-state of cone, semi-cone and hemispherical body.
    3. Interface (interface-ability). Polymorphism is a superclass that, by way of signature, provides a common interface to subclasses, which is implemented by subclasses to refine or overwrite the class.
    4. Flexibility (flexibility). It embodies the flexible operation in the application, and improves the use efficiency.
    5. Simplification (simplicity). Polymorphism simplifies the process of coding and modifying the application software, especially when dealing with the operation and operation of a large number of objects.

After a certain understanding of polymorphism, you can try to look at the following code.
This is a classic polymorphic problem, excerpted from:
Http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx

code example:

    public class Extendstest {public static void main (string[] args) {A A1 = new A ();          A A2 = new B ();          b b = new B ();          c C = new C ();            D d = new D ();      System.out.println ("n" + a1.show (b));      System.out.println ("2--" + a1.show (c));       System.out.println ("3--" + a1.show (d));       System.out.println ("4--" + a2.show (b));      System.out.println ("5--" + a2.show (c));      System.out.println ("6--" + a2.show (d));    System.out.println ("7--" + b.show (b));    System.out.println ("8--" + b.show (c));     System.out.println ("9--" + b.show (d));      }} class A {public String show (D obj) {return ("A and D");      Public String Show (a obj) {return ("A and a");      }} class B extends a{public String show (b obj) {return ("B and B");      Public String Show (A obj) {return ("B and A");           }} class C extends b{ } class D extends b{}   

Operation Result:

1--A and A2--A and A3--A and D4--B and A5--B and A6--A and D7--B and B8--B and B9--A and D

Analysis

①②③ better understand, generally will not be wrong. ④⑤ is a bit confused, why is not the output of "B and B" it?! Let's go back to polymorphism.

Runtime polymorphism is one of the most powerful mechanisms for object-oriented programming code reuse, and the concept of dynamic can also be said to be "one interface, multiple methods". Java's implementation of runtime polymorphism is based on dynamic method scheduling, which is a mechanism for calling overloaded methods at runtime rather than at compile time.

The overridden overriding and overloaded overloading of a method are different manifestations of Java polymorphism.

Overriding overriding is a representation of polymorphism between a parent class and a subclass, and overloading overloading is a representation of polymorphism in a class. If you define a method in a subclass that has the same name and arguments as its parent class, we say that the method is overridden (overriding). When an object of a subclass uses this method, the definition in the subclass is called, and for it the definition in the parent class is "masked". If more than one method with the same name is defined in a class, they either have a different number of arguments or have different parameter types, which is called a method overload (overloading). The overloaded method is to change the type of the return value.

When a Superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the method covered by the quilt class. (However, if you force a superclass to be converted to subclasses, you can call methods that are newly added in the subclass and that are not available in the superclass.) )

All right, let's get this over with. In fact, this involves the priority of the method invocation, with the priority being high to Low: This.show (O), Super.show (O), This.show ((Super) O), Super.show ((Super) O). Let's take a look at how it works.

For example ④,a2.show (b), A2 is a reference variable, the type is a, then this is A2,b is an instance of B, so it went to class A to find show (b obj) method, not found, so to a super (superclass), and a no superclass, So go to the third priority This.show (Super) O, this is still A2, here O is B, (super) O that is (super) B is A, so it goes to class A to find the method of show (a obj), Class A has this method, But since A2 refers to an object of Class B, B overrides the show (a obj) method of a, so it eventually locks to show (aobj) of Class B, and the output is "B and A".

Another example is ⑧,b.show (c), B is a reference variable, type B, then this is B,c is an instance of C, so it to Class B to find Show (C obj) method, not found, instead of to the B's superclass a inside find, a inside also not, so also go to the third priority This.show ( (Super) O), this is B,o C, (super) o i.e. (super) C is B, so it finds the show (Bobj) method in B, found, because B refers to an object of Class B, and therefore directly locks to Class B's show (b obj), the output is "B and B".

According to the above method, the other results can be obtained correctly.
The question goes on, now let's see how the above analysis process reflects the meaning of the words in the blue font. It says that when a superclass object references a variable that references a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the method covered by the quilt class. Take A2.show (b) for a while.

A2 is a reference variable, type A, which refers to an object of B, so the meaning of this sentence is B to decide which method to invoke. Therefore, the show (b obj) of B should be called to output "B and B". But why is it inconsistent with the results from the previous analysis?! The problem is that we don't overlook the second half of the blue font, which is particularly important: the method that is called must be defined in the superclass, that is, the method covered by the quilt class.

Does the show (b obj) inside B have a definition in super Class A? No! That's not to mention being covered. In fact, this statement hides a message: it is still determined by the priority of the method invocation. It finds show (Aobj) in Class A, and if subclass B does not overwrite the show (A obj) method, then it calls a show (Aobj) (because B inherits a, although it is not covered by this method, but inherits this method from Super Class A, in a sense, The method that is called is determined by B, except that the method is implemented in A); now subclass B overrides Show (a obj), so it eventually locks to show (a obj) of B. This is what the meaning of the sentence is.

Other

Reference:
Http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx
Https://www.cnblogs.com/jack204/archive/2012/10/29/2745150.html
12786385

This is the end of this article, thank you for reading! Welcome message and praise, your support is my greatest motivation to write!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

Java Fundamentals Review Three-----Encapsulation, inheritance, and polymorphism

Related Article

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.