Three characteristics of object-oriented programming -- encapsulation, inheritance and polymorphism
jianyuerensheng 2016-06-07 11:41:12 92434 collection 418
Classification column: java improvement article label: java encapsulation inheritance polymorphism
copyright
1, Encapsulation
Encapsulation literally means packaging. The professional point is information hiding. It refers to the use of abstract data types to encapsulate data and data-based operations together to form an inseparable independent entity. The data is protected inside the abstract data types and hide the internal details as much as possible, Only some external interfaces are reserved to make them contact with the outside world. Other objects of the system can only communicate and interact with this encapsulated object through authorized operations wrapped outside the data. In other words, the user does not need to know the internal details of the object, but can access the object through the external interface provided by the object. For encapsulation, an object encapsulates its own properties and methods, so it can complete its own operations without relying on other objects. There are three benefits to using encapsulation: 1,Good packaging can reduce coupling. 2,The structure inside the class can be modified freely. 3,You can have more precise control over members. 4,Hide information and realize details. Encapsulation privatizes the properties of an object and provides methods for properties that can be accessed by the outside world. If we don't want to be accessed by the outside world, we don't need to provide methods for external access. However, if a class does not provide methods for external access, then the class is meaningless. public class Husband { /* * Encapsulation of attributes * A person's name, gender, age and wife are his private attributes */ private String name ; private String sex ; private int age ; private Wife wife; /* * setter(),getter()It is the external development interface of this object */ public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setWife(Wife wife) { this.wife = wife; } } Encapsulation allows us to easily modify the internal implementation of a class without modifying the customer code that uses the class. Member variables can be controlled more accurately.
-
public void setAge(int age) {
-
if(age > 120){
-
System.out.println("ERROR: error age input...."); //Prompt error message
-
}else{
-
this.age = age;
-
}
-
}
-
public String getSexName() {
-
if("0".equals(sex)){
-
sexName = "female";
-
}
-
else if("1".equals(sex)){
-
sexName = "male";
-
}
-
else{
-
sexName = "Simon?";
-
}
-
return sexName;
-
}
2, Inherit
2.1 inheritance overview
Inheritance is a technology that uses the definition of an existing class as the basis to establish a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but it cannot selectively inherit the parent class. By using inheritance, we can easily reuse the previous code and greatly improve the efficiency of development. Inheritance describes“ is-a"If there are two objects A and B,If it can be described as“ A yes B",Can represent A inherit B,among B Is what the inheritee calls a parent or superclass, A Is what the inheritor calls a subclass or derived class. In fact, the successor is the specialization of the decedent. It not only has the characteristics of the decedent, but also has its own unique characteristics. For example, cats have the characteristics of catching mice, climbing trees and other animals. At the same time, in the inheritance relationship, the successor can completely replace the successor, but not on the contrary. For example, we can say that the cat is an animal, but we can't say that the animal is a cat. In fact, for this, we call it "upward transformation". Admittedly, inheritance defines how classes relate to each other and share features. For several identical or familiar classes, we can abstract their common behavior or genus and define it as a parent class or super class, and then inherit the parent class with these classes. They can not only have the properties and methods of the parent class, but also define their own unique properties or methods. At the same time, you need to remember three sentences when using inheritance: 1,A subclass has a non parent class private Properties and methods of. 2,Subclasses can have their own properties and methods, that is, subclasses can extend the parent class. 3,Subclasses can implement the methods of their parent classes in their own way. (introduced later). Learning and inheritance must be based on these three things: constructors protected Keywords, upward transformation
2.2 constructor
From the above, we know that subclasses can inherit the properties and methods of the parent class, except those private There is another thing that subclasses cannot inherit---Constructor. For constructors, it can only be called, not inherited. Call the constructor of the parent class. We use super()Just. The construction process is "outward" from the parent class, that is, the construction is completed from the parent class to the child class level by level. And we don't show a constructor that references the parent class, which is java The cleverness of: the compiler will call the constructor of the parent class to the subclass by default. However, this constructor that calls the parent class by default has a premise: the parent class has a default constructor. If the parent class does not have a default constructor, we need to show the use of super()To call the parent constructor, otherwise the compiler will report an error: unable to find a constructor that conforms to the parent form. Just for subclasses,The correct initialization of its constructor is very important,And only if only one method can guarantee this: in the constructor, the parent class constructor is called to complete the initialization, and the parent constructor has all the knowledge and ability needed to initialize the parent class.
For inheritance, the subclass will call the constructor of the parent class by default, but if there is no default parent class constructor, the subclass must display the constructor of the specified parent class and must be the first thing to do in the subclass constructor (the first line of code).
2.3 protected keyword
private Access modifier is the best choice for encapsulation, but it is only based on the ideal world. Sometimes we need to hide some things from the world as much as possible, but still allow subclass members to access them. It needs to be used at this time protected. about protected In terms of, it indicates that in terms of class users, he is private,However, it is accessible to any subclass that inherits from this class or any other class in the same package.
2.4 upward transformation
In the above inheritance, we talk about inheritance is-a The relationship between cats and animals, so we can say that cats are animals, or cats are a kind of animals. In this way, treating cats as animals is an upward transformation.
-
public class Person {
-
public void display(){
-
System.out.println("Play Person...");
-
}
-
static void display(Person person){
-
person.display();
-
}
-
}
-
public class Husband extends Person{
-
public static void main(String[] args) {
-
Husband husband = new Husband();
-
Person.display(husband); //Upward transformation
-
}
-
}
Here we go through person display(husband). This sentence shows that husband is a person type.
Converting a subclass into a parent class moves upward in the inheritance relationship, so it is generally called upward transformation. Because the upward transformation is from a special type to a more general type, it is always safe. The only possible change is the loss of properties and methods. This is why the compiler still allows upward transformation when "transformation has not been explicitly expressed" and "special tags have not been specified".
2.5 prudent inheritance
Here we need to make it clear that inheritance has the following defects:
1. If the parent class changes, the child class must change.
2. Inheritance breaks the encapsulation. For the parent class, its implementation details are transparent to the child class.
3. Inheritance is a strong coupling relationship.
So when we use inheritance, we need to be sure that using inheritance is indeed an effective and feasible way. So do you want to use inheritance? < Think in java>Ask whether the parent-child class needs to be transformed to the upper class. If you have to make an upward transition, inheritance is necessary, but if not, you should consider whether you need to inherit.
3, Polymorphism
3.1 overview
The so-called polymorphism refers to the specific type pointed to by the reference variable defined in the program and the method call issued through the reference variable. It is not determined during programming, but only during the operation of the program, that is, a reference variable will point to the instance object of which class, and the method call issued by the reference variable is the method implemented in which class, It can only be determined during the running of the program. Because the specific class is determined only when the program is running, so that the reference variable can be bound to various class implementations without modifying the source program code, resulting in the change of the specific method called by the reference, that is, the specific code bound when the program is running can be changed without modifying the program code, so that the program can select multiple running states, This is polymorphism.
Therefore, for polymorphism, we can summarize as follows:
Due to the upward transformation, the parent class reference pointing to the subclass can only access the methods and properties owned by the parent class. For the methods existing in the subclass but not in the parent class, the reference cannot be used, although it overloads the method. If the subclass overrides some methods in the parent class, these methods defined in the subclass must be used when calling these methods (dynamic connection and dynamic call).
For object-oriented, polymorphism can be divided into compile time polymorphism and run-time polymorphism. Polymorphism during editing is static, which mainly refers to the overloading of methods. It distinguishes different functions according to different parameter lists. After editing, it will become two different functions, which is not polymorphic at run time. The runtime polymorphism is dynamic, which is realized by dynamic binding, that is, what we call polymorphism.
3.2 realization conditions of polymorphism
At the beginning, we mentioned inheritance, which is preparing for the implementation of polymorphism. Subclass Child Inherit parent class Father,We can write a parent type reference to a child class, which can handle both the parent class and the child class Father Object, you can also handle subclasses Child Object. When the same message is sent to a subclass or parent object, the object will perform different behaviors according to the reference to which it belongs. This is polymorphism. That is, polymorphism is that the same message makes different classes respond differently.
There are three necessary conditions for realizing polymorphism in Java: inheritance, rewriting and upward transformation.
Inheritance: in polymorphism, there must be subclasses and parent classes with inheritance relationship. Override: subclasses redefine some methods in the parent class. When these methods are called, the subclass's methods will be called. Upward Transformation: in polymorphism, you need to assign the reference of the subclass to the parent object. Only in this way can the reference have the skills to call the methods of the parent class and the subclass. Only when the above three conditions are met can we use unified logic implementation code to deal with different objects in the same inheritance structure, so as to execute different behaviors. about Java Generally speaking, its polymorphic implementation mechanism follows a principle: when a superclass object references a subclass object with a reference variable, the type of the referenced object rather than the type of the reference variable determines whose member method to call, but the called method must be defined in the superclass, that is, the method covered by the subclass.
3.3 implementation form
There are two forms of polymorphism in Java: Inheritance and interface.
3.2.1 polymorphism based on inheritance implementation
The implementation mechanism based on inheritance is mainly reflected in the rewriting of some methods by the parent class and one or more subclasses inheriting the parent class. The rewriting of the same method by multiple subclasses can show different behaviors. The polymorphism based on inheritance implementation can be summarized as follows: for the parent type that references a subclass, when processing the reference, it is applicable to all subclasses that inherit the parent class. Different subclass objects have different implementation of methods and different behaviors generated by executing the same action. If the parent class is an abstract class, the subclass must implement all the abstract methods in the parent class. In this way, all subclasses of the parent class must have a unified external interface, but their internal specific implementations can be different. In this way, we can use the unified interface provided by the top-level class to deal with the methods of this level.
3.2.2 polymorphism based on interface implementation
Inheritance is embodied by rewriting several different subclasses of the same method of the parent class, which can be embodied by implementing the interface and covering several different classes of the same method in the interface. In interface polymorphism, the reference to the interface must be an instance program that specifies a class that implements the interface. At run time, the corresponding method is executed according to the actual type of object reference. Inheritance is single inheritance, which can only provide a consistent service interface for a group of related classes. However, the interface can be multi inheritance and multi implementation. It can use a group of related or unrelated interfaces for combination and expansion, and can provide a consistent service interface. So it has more flexibility than inheritance.
3.2.3 analysis of classic examples
public class A { public String show(D obj) { return ("A and D"); } public String show(A obj) { return ("A and A"); } } public class B extends A{ public String show(B obj){ return ("B and B"); } public String show(A obj){ return ("B and A"); } } public class C extends B{ } public class D extends B{ } public class Test { 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("1--" + 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)); } }
Operation results:
The analysis is as follows:
① ② ③ it's easy to understand and generally won't make mistakes. ④ ⑤ I'm a little confused. Why isn't "B and B" output?
When a superclass object references a subclass object with a reference variable, the type of the referenced object rather than the type of the reference variable determines whose member method to call, but the called method must be defined in the superclass, that is, the method overridden by the subclass. (however, if you force the superclass to be converted into a subclass, you can call the methods newly added in the subclass but not in the superclass.)
In the inheritance chain, there is a priority for the invocation of object methods: this show(O),super.show(O),this.show((super)O),super.show((super)O).
A, B, C and D in the above procedure have the following relationship:
Analysis 4:
a2.show(b),a2 Is a reference variable of type A,be this by a2,b yes B An instance of, so it goes to the class A Look inside show(B obj)Method, not found, so to A of super(Superclass)Looking, and A There are no superclasses, so go to third priority this.show((super)O),this Still a2,here O by B,(super)O Namely(super)B Namely A,So it goes to class A Look inside show(A obj)Methods, classes A There is this method, but because a2 The reference is a class B An object of, B Covered A of show(A obj)Method, so you end up locking to the class B of show(A obj),Output as"B and A".
Analysis 5:
a2.show(c),a2 yes A Type, so this On behalf of A,a2.show(c),It's in A Class was not found, so A Found in superclass of(super),because A No superclass( Object Except), so jump to the third level, that is this.show((super)O),C The superclasses are B,A,therefore(super)O by B,A,this similarly A,Here A Found in show(A obj),At the same time, due to a2 yes B Class and B Class overridden show(A obj),Therefore, subclasses will eventually be called B Class show(A obj)Method, the result is B and A.
Analysis 8:
b.show(c),b Is a reference variable of type B,be this by b,c yes C An instance of, so it goes to the class B look for show(C obj)Method, not found, turned to B Super class of A Look inside, A There's nothing in it, so it's also transferred to the third priority this.show((super)O),this by b,O by C,(super)O Namely(super)C Namely B,So it goes B Look inside show(B obj)Method, found, because b The reference is a class B An object, so it is locked directly to the class B of show(B obj),Output as"B and B". In the same way, I can confirm other answers.
When a superclass object references a subclass object with a reference variable, the type of the referenced object rather than the type of the reference variable determines whose member method to call, but the called method must be defined in the superclass, that is, the method overridden by the subclass. Here we use an example to illustrate the meaning of this sentence: A2 show(b);
here a2 Is a reference variable, is A Type, which refers to B Object, so according to the meaning of the above sentence, it means yes B To decide whose method to call,therefore a2.show(b)Should be called B Medium show(B obj),The result should be“ B and B",But why is it different from the previous running results? Here we ignore the following sentence "the called method must be defined in the superclass" show(B obj)stay A Does it exist in the class? It doesn't exist! So this sentence doesn't apply here? So is this sentence wrong? No! In fact, this sentence also implies this sentence: it still has to be recognized according to the priority of the calling method in the inheritance chain. That's why it's here A Found in class show(A obj),At the same time, due to B This method is overridden, so it will be called B Class, otherwise it will be called A Class.
reference material:
http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx
http://blog.csdn.net/chenssy/article/details/12786385
--------
Copyright notice: This article is the original article of CSDN blogger "jianyuerensheng", which follows the CC 4.0 BY-SA copyright agreement. For reprint, please attach the source link of the original text and this notice.
Original link: https://blog.csdn.net/jianyuerensheng/article/details/51602015