Three features of Java (encapsulation, polymorphism and inheritance)

Three features of Java (encapsulation, polymorphism and inheritance)

encapsulation

1. Meaning

Encapsulation: it refers to a method that wraps, hides, and surrounds the implementation details of an abstract function interface. Data can only be accessed through a defined public interface.

2. Purpose

Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being randomly accessed by the code defined by the external class. Programmers can modify their own implementation code without modifying the program fragments that call their code. It can make the code easier to understand and maintain, and also strengthen the security of the code.

3. Examples

public class Man
{
//The encapsulation of attributes, a person's name, age and wife are the private attributes of the object (person)
private String name;
private int age;
private Woman wife;
}

4. Advantages

Through encapsulation, the information can be hidden, the internal structure of the class can be changed, the member variables can be controlled more accurately, and the reusability of the code is improved.

5. Shortcomings

Encapsulating some details makes it impossible to access these details directly, which increases the difficulty of access and affects the efficiency of execution.

inherit

1. Meaning

Inheritance is to derive a new class from an existing class. The new class can absorb the data properties and behaviors of the existing class and expand new capabilities. In other words, these classes have common properties and behaviors. The existing class is called the parent class, and the new class is called the child class. The child class inherits the characteristics and behavior of the parent class, so that the child class object (instance) has the instance domain and method of the parent class, or the child class inherits the method from the parent class, so that the child class has the same behavior as the parent class.

2. Inheritance format of class``

class Parent class {
}
class Subclass extends Parent class {
}

3. Examples

Note: this code refers to wing_ Of frgt10 Blog

class Person1 {
    public String name="xiaomiao";
    public int age=20;
}
class Student extends Person1 {
    void study() {
        System.out.println("I can study!");
    }
}
public class JiCheng {
    public static void main(String args[]) {
        Student stu = new Student();
        stu.study();
        System.out.println("full name:" + stu.name + "\n" + "Age:" + stu.age);
    }
}

Operation results:
I can study!
Name: xiaomiao
Age: 20

Although the student class does not declare the name and age of the student, because it inherits person1, the name and age are also output after instantiation.

4. Inherited type

5. Inherit keywords

(1) extends keyword

In Java, class inheritance is a single inheritance, that is, a subclass can only have one parent class, so extensions can only inherit one class.
In the above example, the extends keyword is used. There is no example here.

(2) implements keyword

Using the implements keyword can make java have the feature of multi inheritance in a disguised way. If the scope of use is class inheritance interface, you can inherit multiple interfaces at the same time (the interface is separated by commas).
Examples are as follows:

public interface A {
    public void eat();
    public void sleep();
}
public interface B {
    public void show();
}
public class C implements A,B {
}

(3) super and this keywords

Super keyword: we can access the members of the parent class through the super keyword, which is used to reference the parent class of the current object.
this keyword: refers to your own reference.
Examples are as follows:

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}
class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void eatTest() {
    this.eat();   // this calls its own method
    super.eat();  // super calls the parent class method
  }
}
public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();
    Dog d = new Dog();
    d.eatTest();
  }
}

The operation result is:
animal : eat
dog : eat
animal : eat

It can be found that when d.eatTest() calls void eatset(), there are two different running results. This is because the meaning of this and super in void eatTest() is different from that of the calling method, resulting in the output of two different results.

Through this example, we can intuitively feel the difference between super and this keywords.

(4) final keyword

Final keyword declares that the class can be defined as the final class that cannot be inherited. The String class in Java is a final class. If the member variable or local variable is modified as final, the modified variable is immutable, that is, it is a constant.

6. Advantages

(Note: the advantages and disadvantages of inheritance are extracted from _Jason_PC.) Blog)
● code sharing to reduce the workload of creating classes. Each subclass has the methods and attributes of the parent class;
● improve code reusability;
● the subclass can look like the parent, but it is different from the parent. "The dragon begets the dragon, the Phoenix begets the Phoenix, and the mouse is born to make a hole" means that the son has the "seed" of the father, "and" there are no two identical leaves in the world "means that the son is different from the father;
● improve the scalability of the code, and the method of realizing the parent class can "do whatever you want". You can't see that many extension interfaces of open source frameworks are completed by inheriting the parent class.

7. Shortcomings

● inheritance is intrusive. As long as you inherit, you must have all the properties and methods of the parent class;
● reduce code flexibility. Subclasses must have the attributes and methods of the parent class, so that there are more constraints in the free world of subclasses;
● enhanced coupling. When the constants, variables and methods of the parent class are modified, the modification of the child class needs to be considered, and in the absence of specification, this modification may lead to very bad results - large pieces of code need to be refactored.
Link: link.

polymorphic

1. Meaning

Polymorphism means that objects of different subtypes are allowed to respond differently to the same message. The same operation acts on different objects, which can have different interpretations and produce different execution results. Polymorphism is divided into compile time polymorphism and run-time polymorphism.
Image example:

Both color printer and black-and-white printer print the same photo at the same time, but due to their different functions, they print out pictures with different effects. In daily life, the same dress and two different people wear it will have different effects for various reasons. In fact, these reflect polymorphism in essence.

2. Three conditions for polymorphic implementation

(1) Inherit
(2) Rewrite
(3) A parent class reference points to a child class object

3. Three ways to realize polymorphism

(1) Rewrite
(2) Interface
Interface polymorphism refers to the same type of interface with different implementation methods.
(3) Abstract classes and abstract methods

4. Examples

Preconditions for use: a. inheritance of classes b. overriding of parent methods by subclasses
Usage: point to the object of the subclass through the reference of the parent class
(Note: this code comes from shuaiflying Blog)

public class Person {
    public void eat(){
        System.out.println("People eat");
    }
}
class Man extends Person{
    public void eat(){
        System.out.println("Men eat");
    }
}
//Preconditions for the use of polymorphism of subclass objects: 1 There should be class inheritance 2 There should be subclasses that override the methods of the parent class
public class Test {
    public static void main(String[] args) {
   //Polymorphism of subclass objects: the reference of the parent class points to the subclass object
    Person p=new Man();//Upward transformation
   //Virtual method call: refers to the entity of the subclass object through the reference of the parent class. When calling the method, it actually executes the method of the subclass overriding the parent class
    p.eat();
    }
},
The use of subclass polymorphism is to use the reference of the parent class to point to the object of the subclass, and then the virtual method calls the subclass to override the method of the parent class
 In addition, add that the polymorphism of subclass objects does not apply to attributes
public class Person {
    int id=101;
    public void eat(){
        System.out.println("People eat");
    }
}
class Man extends Person{
    int id=102;
    public void eat(){
        System.out.println("Men eat");
    } 
}
public class Test {
    public static void main(String[] args) {
          Person p=new Man();
          p.eat();
          System.out.println(p.id);//The output is the id attribute of the Person object
    }
}

The operation result is:

5. Advantages

  1. Replaceability
  2. Extensibility
  3. Interface
  4. flexibility
  5. Simplification

6. Shortcomings

Polymorphism can only use the reference of the parent class to access the members of the parent class, but not the specific functions of the child class.

summary

By studying the three characteristics of Java, I have a preliminary understanding and understanding of encapsulation, inheritance and polymorphism, their implementation methods, and their advantages and disadvantages.

reference material:
Java Tutorial

Added by khjart on Mon, 07 Mar 2022 15:41:01 +0200