Java encapsulation, inheritance, polymorphism, interface learning summary

### One: Encapsulation in
Java refers to a method of partially wrapping and hiding the implementation details of abstract functional interfaces. 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. To access the code and data of this class, it must be controlled through a strict interface. The main function of encapsulation is that we can modify our own implementation code without modifying the program fragments that call our code. Appropriate packaging can make the code easier to understand and maintain, and also enhance the security of the code.
*** Package advantages ***
    1 A good package can reduce coupling.
    The internal structure of category 2 can be modified freely.
     3 Member variables can be controlled more accurately.
     4 Hide internal information and realize details.
     *** Steps to implement java encapsulation ***
     1 Modify the visibility of attributes, generally set to private, only restrict access to this class
`` `java
private String name;
private int num;
` ``
  2 Provide for each value attribute External public method (setter, getter accessor)
  shortcut: alt + shift + s (select Generate getters and setters)
`` `java
    private String name;
    private int age;
    public String getName () {
        return name;
    }
    public void setName (String name) {
        this.name = name;
    }
    public int getAge () {
        return age;
    }
    public void setAge (int age) {
        this.age = age;
    }
`` `
### Two:
inheritance That is, the subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class.

*** Why do you need to inherit? ***
Reduce code redundancy, extract code with common behavior, encapsulate it as a parent class, and inherit the parent class from the child class, reduce the bloat of the code and facilitate later modification!

 *** Inherited features ***
 1 Multiple inheritance is not supported in Java, but multiple inheritance is supported.
 ! [Picture from rookie tutorial] (https://img-blog.csdnimg.cn/20200412103746375.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dX_Ng3_Ax4, ) 2 The subclass has all the non-private attributes and methods of the parent class.
 3 Subclasses can have their own properties and methods, that is, the extension of the subclass to the parent class
 4 The subclass can implement the methods of the parent class in its own way (that is, the subclass rewrites the parent class method)
 5 Increased class coupling Inheritance shortcomings: the higher the coupling, the worse the independence of the code.)
 
*** Keyword of inheritance ***
Single inheritance in java, extends can only inherit one class

`` `java
class A extends B {}
` ` `
** super and this keywords **
super: Use the super keyword to access the members of the current parent class, used to apply the current object ’s parent class
this: a reference to the current object (pointing to yourself)
Example:

` `` java
public class Pet {
    void run () {
        System.out.println ("pet is running");
    };
}

public class Cat extends Pet {
    void run () {
        System.out.println ("Cat is running");
    }
    void runTest () {
        super.run ();
        this.run ();
    }
}

public class Test {
    public static void main (String [] args) {
        Pet pet = new Pet ();
        pet.run ();
        Cat cat = new Cat ();
        cat.runTest ();
    }
}

`` `
    Output result For:
    pet is running
    pet is running
    Cat is running

Note: The class modified by the final keyword is defined as the final class and cannot be inherited
*** Constructor ***
Subclass does not inherit the constructor of the parent class (constructor or constructor ), Just call (show or implicit). If the constructor of the parent class has parameters, the subclass must explicitly call the constructor of the parent class with the super keyword with appropriate parameters.
If the constructor of the parent class has no parameters, it is not required to be explicitly called by the super keyword, and the system will call the parent parameterless constructor by default.
Example: (from runoob.com)

`` `java

class SuperClass {
  private int n;
  SuperClass () {
    System.out.println (" SuperClass () ");
  }
  SuperClass (int n) {
    System.out.println ("SuperClass (int n)");
    this.n = n;
  }
}
//
SubClass extends class SubClass extends SuperClass {
  private int n;
 
  SubClass () {// Automatically calls the parent class without parameters Constructor
    System.out.println ("SubClass");
  }  
 
  public SubClass (int n) {
    super (300); // call constructor with parameters in parent class
    System.out.println ("SubClass (int n) : "+ n);
    this.n = n;
  }
}
// SubClass2 class inherits
class SubClass2 extends SuperClass {
  private int n;
 
  SubClass2 () {
    super (300); // calls the constructor
    System with parameters in the parent class .out.println ("SubClass2");
  }  
 
  public SubClass2 (int n) {// Automatically call the parent parameterless constructor
    System.out.println ("SubClass2 (int n):" + n);
    this.n = n;
  }
}
public class TestSuperSub {
  public static void main (String args []) {
    System.out.println ("- ---- SubClass class inheritance ------ ");
    SubClass sc1 = new SubClass ();
    SubClass sc2 = new SubClass (100);
    System.out.println (" ------ SubClass2 class inheritance- ----- ");
    SubClass2 sc3 = new SubClass2 ();
    SubClass2 sc4 = new SubClass2 (200);
  }
}
` `` The
    output is:
    ------ SubClass class inheritance ------
    SuperClass ()
    SubClass
    SuperClass (int n)
    SubClass (int n): 100
    ------ SubClass2 class inheritance ------
    SuperClass (int n)
    SubClass2
    SuperClass ()
    SubClass2 (int n): 200
### Three: Polymorphism
refers to the ability of the same behavior to have multiple expressions or forms. Polymorphism is the same interface, using different instances to perform different operations. When the same event occurs on different objects, there will be different execution methods.
*** Advantages of polymorphism ***
1 Eliminate coupling between types
2 Replaceability
3 Scalability
4 Interface
5 Flexibility
6 Simplification
*** Necessary conditions for the existence of polymorphism ***
1 Inheritance
2 Rewrite
3 Parent class reference points to subclass object
Example:

`` `java
Pet cat = new Cat ();
` ``
When using polymorphic call methods, first check whether the parent class has a modified method, if it does not exist, then compile If there is an error, call the method with the same name in the subclass.
Benefits: It can make the program have a good expansion, and can handle all types of objects universally.
Example: (from runoob.com)

`` `java

public class Test {
    public static void main (String [] args) {
      show (new Cat ()); // call show method with Cat object
      show (new Dog ()); // Call show method with Dog object
                
      Animal a = new Cat (); // Upward transformation  
      a.eat (); // Call Cat's eat
      Cat c = (Cat) a; // Downward transformation  
      c.work (); // The work of Cat is called
  }  
            
    public static void show (Animal a) {
      a.eat ();  
        // Type judgment
        if (a instanceof Cat) {// Cat does things
            Cat C = (Cat) a;  
            c.work ();  
        } the else IF (a dog the instanceof) {// do dog
            dog C = (dog) a;  
            c.work ();  
        }  
    }  
}
 
abstract class Animal {  
    abstract void eat ();  
}  
 
class Cat extends Animal {  
    public void eat () {  
        System.out.println ("吃鱼");  
    }  
    public void work () {  
        System.out.println ("catch mouse");  
    }  
}  
 
class Dog extends Animal {  
    public eAT void () {  
        System.out.println ( "eat bones");  
    }  
    public void Work () {  
        System.out.println ( "housekeeping");  
    }  
}

`
    result:
    fish
    and mouse
    a bone,
    Watching the
    fish and
    catching the mouse
*** polymorphic implementation: ***
1 rewrite
2 interface
3 abstract class and abstract method

### Four: interface
interface (interface), a class through the inheritance of the interface to achieve Abstract method inside the interface.
Note: The interface is not a class. The class describes the properties and methods of the object, and the interface contains the methods to be implemented by the class. Unless the class implementing the interface is an abstract class, all methods in the interface must be implemented.
Interfaces cannot be instantiated, but they can be implemented. A class that implements an interface must implement all abstract methods in the interface, otherwise define this class as an abstract class.
*** Similarities between interfaces and classes ***
1 An interface can have multiple methods.
2 The interface saves the file ending in .java, and the file name uses the interface name.
3 The bytecode file of the interface is saved in .class.
4 The bytecode file saved by the interface must be in the same directory as the package name.
*** Difference between interface and class ***
1 Interface cannot instantiate object
2 No construction method in
interface 3 All methods in interface are abstract methods and all variables are static variables.
4 The variables in the interface can only be public final static
5 The interface supports multiple inheritance
6 The interface is not inherited by the class, but is to be implemented by the class
*** Features to be noted for the
interface *** 1 Every method in the interface is Abstract (abstract) is public abstract (other modifiers will compile errors)
2 Variables in the interface are designated as public, static, final, (private will compile errors)
3 The method in the interface is an abstract method, not in the interface Implementation can only be achieved by the class that implements the interface.
** The difference between an abstract class and an interface **
1 The methods in an abstract class can have a method body, the methods in the interface are all abstract methods, and cannot have a method body
2 The member variables of the abstract class can be of any type, only in the interface Is public static final
3 There can be no static static code blocks and static methods in the interface. (After jdk1.8, there can be static code and method body)
4 A class can only inherit an abstract class, and a class can implement multiple interfaces
*** interface declaration ***
use interface keyword
example:

`` ` java
public interface Pet {
// public static final member variable
// abstract method
public void eat ();
public abstract void run ();

}
`` `
***
    implementation of the interface *** use the implements keyword (you can achieve more Interfaces, separated by ","
    Example:
    

`` `java
public abstract class Door {

    public abstract void open ();

    public abstract void close ();
}

public interface DoorBell {
    void takePictures ();
}

public interface Lock {

    public abstract void lockUp ();

    void openLock ();
}

public class TheftprootDoor extends Door implements Lock,DoorBell {

    @Override
    public void lockUp() {
        // TODO Auto-generated method stub
        System.out.println("上锁");
    }

    @Override
    public void openLock() {
        // TODO Auto-generated method stub
        System.out.println("开锁");
    }

    @Override
    public void open() {
        // TODO Auto-generated method stub
        System.out.println("开门");
    }

    @Override
    public void close() {
        // TODO Auto-generated method stub
        System.out.println("关门");
    }

    @Override
    public void takePictures () {
        // TODO Auto-generated method stub
        System.out.println ("photographed");
    }
}

    public static void main (String [] args) {
        // TODO Auto-generated method stub
        TheftprootDoor thef = TheftprootDoor new new ();
        thef.close ();
        thef.lockUp ();
        thef.openLock ();
        thef.open ();
        thef.takePictures ();
    }

`` `

    code execution results:
    closing
    lock
    to unlock
    the door
    to take pictures

 ** Notes when rewriting methods
 in interfaces : ** Class 1 cannot throw exceptions when implementing methods in interfaces, and can only throw exceptions in interfaces or abstract classes that inherit interfaces.
 When rewriting methods in category 2, ensure the same method name, or compatible return value types.
 3 If the class implementing the interface is an abstract class, there is no need to implement the method of the interface.
 
 ** When implementing interfaces,
 please note: ** 1 A class can implement multiple interfaces (separated by ",")
 2 A class can only inherit one class, but can implement multiple interfaces
 3 An interface can inherit another interface ( Similar to class inheritance)
 
*** Multiple inheritance of interfaces *** In
Java, classes do not allow multiple inheritance, but interfaces can implement multiple inheritance, use the extends keyword, separated by ","

java
public interface Cat extends Run, Eat, Swim {}
`` `
*** Mark interface ***
An interface without any methods is called a mark interface.

The purpose of marking the interface:
1 Establish a common parent interface
2 Add a data type to a class:


(Collated on 2020/4/12, if there are errors, I hope everyone can put forward.)

Guess you like

Origin www.cnblogs.com/ambition26/p/12684707.html
Recommended