Introduction to Java object-oriented Basics

✏️ Object oriented content core in Java:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism


❓ What is encapsulation?

I wonder if you robbed the remote control of the TV when you were a child? The remote control is the result of packaging.

It's a simple way to pack everything in a black box.

Similarly, switch to Java. Since Java is composed of classes one by one, let's put "them" into Java classes.

You ask who they are? They are the attributes (data) and methods (what we call functions, that is, operations on data) of the class. In other words, if this class wants to be useful, you must at least define who you did what to. It can be seen that encapsulation is nothing more than encapsulating attributes and methods to simulate a "black box service"

☕ Java encapsulation implementation

public class Person{
   private String name;
   private int age;   // Set the access permissions of the name and age variables to private   
   public void setName(String name){ = name;
    public String getName(){
        return name;//return is OK
    }                 // Define the operation methods of the name attribute, namely getter and setter

From the above example, we can see that the steps of encapsulation are:

  1. Attribute privatization -------- > set the more Private attribute to Private
  2. getter() and setter() methods for creating private properties

In this way, we can package and encapsulate the attributes and the internal implementation. Therefore, generally speaking, encapsulation is an operation that simulates the black box. It uses the private access modifier and the corresponding getter() and setter() methods to simulate the black box and provide external services.


Inheritance is also easy to understand. Inheriting family property, inheriting the throne and so on are the same concepts; We can also say that inheritance is a kind of "sharing", in which the inherited keyword is: extends

☕ Java inheritance implementation

public class Person{
    private String name;
    private int age;
    public double salary;
    //... The Setter and Getter methods corresponding to each attribute (the default is public), which will not be described here one by one
class Student extends Person{
    private double weight; //Student defines his own unique weight
    public void study(){
        System.out.println("I am learning Java,Do not disturb.")

The above implements a very simple inheritance. The Student class inherits from the Person class, that is, the Student shares the properties and methods in the Person class; Some people will say: "inheritance mechanism easily breaks the encapsulation mechanism"! Is that true? Let's first look at the following inheritance rules:

  1. When the subclass and the parent class are in the same package, the subclass can inherit the member variables and methods of public, procted and default access level in the parent class.

  2. When the subclass and the parent class have different packages, the subclass inherits the member variables and methods of the public and protected access levels in the parent class.

🤠 So to some extent, it is true, but it can be broken conditionally. As shown in the above code, although student inherits Person, it cannot inherit the attributes and methods modified by private in Person, such as' name 'and' age '; Students can inherit the salary attribute and the corresponding setter and getter methods of each attribute.

❓ How to inherit, how not to inherit?

☕️ Coding Show

//In main method
Student student = new Student();  //Instantiate a Student object and point to it with a reference of Student type = "Yang Chaoyue"; // Wrong! Because Student cannot inherit name (private protection mechanism)
student.salary = "3000.0"; //Successful assignment, inherited from the salary of Perosn, can be used for your own use without defining it yourself

❓ Since we can't inherit the name and age attributes of Person, isn't our inheritance mechanism a disability mechanism?

🍦 Don't forget that our Person class encapsulates the getter and setter methods of the corresponding attributes. They are all public permissions. Our students inherit the getter and setter methods of Person. They are the "interface" of our encapsulation mechanism to provide external services. We can use them to complete the disguised value and assignment of Student type name;

☕️Coding show

//In main method
Student student = new Student();
student.setName("Liu Yifei");
System.out.println(student.getName());//Printed by: Liu Yifei
//The same is true for inaccessible age s

🔐 What is the role of inheritance mechanism?

🔑 1. Inheritance can be understood as a concept of "sharing"; Just like sharing bicycles, there is no need for everyone to have their own bicycles, because we can also use "public" (projected on public and protected access rights) bicycles to complete our journey;

🔑 2. Inheritance is to better encapsulate and realize the sharpening (expansibility) of functions. For example, the student class can be more specific than the Person class. For example, we have defined the study method in the student class, which is a student's unique method and attribute, making the Person class more specific. In the later polymorphic characteristics, it is easier to realize Java's control over the "abstraction ability" of the class.

Polymorphism (key)

🌻 Polymorphism is based on Inheritance and encapsulation. Why? Because packaging can be regarded as a "black box"; Inheritance can be regarded as a kind of "sharing", so polymorphism can be understood as a kind of "transformation" based on the interaction between them**

☕️ Coding Show

public class Animal{  //Let's first create a parent class of animals
    private String name;
    private int age;
    private double weight;
    public void setName(String name){ = name;
    public String getName(){
    public void eat(){
        System.out.println("Eat eat eat");
    //.... Getter () and setter () methods for age and weight
class Cat extends Animal{  // Define a kitten
	  private int height; //Define personalized attributes - how high can you jump
      public void eat(){  //Method rewrite
          System.out.println("I love the taste of saury");
      public void cry(){
          System.out.println("cat ");
  	//... getter and setter methods of height

class Dog extends Animal{  //Define a puppy
    private int height;
    public void eat(){ //Method rewrite
        System.out.println("I love the taste of sauce big bone");  //Note that there is no / / coverage relationship with the eat method in cat, because they are not parent-child relationship, but inherit Animal at the same layer
    public void dark(){
        System.out.println("I'm a single dog, and I only bark");

🍂 Let's let the cat and dog inherit the parent class Animal and override the eat() method of the parent class. Next, let's see how Java polymorphism is implemented:

Animal animal = new Dog(); //The compilation type of animal is animal and the running type is Dog
animal = new Cat(); //The compilation type of animal is animal, and the running type becomes Cat
//In other words, anima's downward transformation can be turned at will
//The compilation type is directly determined and cannot be changed; However, the instantiation type at runtime can be changed;

🌜 The mechanism of polymorphism is mainly reflected in methods and objects. Overloading and rewriting are the most commonly used methods, which are relatively simple and easy to understand;

In terms of objects, we need to pay attention to the following four points:

  1. The compile type and run type of an object can be inconsistent
  2. The compilation type is determined when defining the object and cannot be changed
  3. The operation type can be changed
  4. When compiling type definitions, you should look at the left side of =, and the right side of running type =

😎 That is, the reference of the parent class can point to the object of the child class; The analogy of the relationship between compiled type and runtime type 1 is "wolf in sheep's clothing". It looks like a sheep (compiled type), but it is actually a wolf (runtime type). In fact, the compiled class type (Animal) delineates the callable range of animal, because Javac does not allow compiled types to call methods unique to subclasses, but only common methods; However, once the class is loaded into the runtime after the JVM, Java can process the instance object at runtime. The method defined in the subclass is called; If it is not in the subclass, go to the parent class to find it. If it is not in the parent class, keep querying upward until the object type is found. If it is not found, an error will be reported.

Animal animal = new Dog(); 
animal.dark(); //  Error!  Because compiled types cannot call subclass specific methods, they need to be transformed downward;
(Dog)animal = new Dog();
animal.drak(); //Successfully called

"Memory address" = = "runtime instance type"

The inheritance mechanism makes the system no longer "embarrassed", and the method can maintain "heartbeat monitoring" with the instance type at runtime; However, the attribute will not keep in touch with the runtime type all the time, that is, the runtime dynamic binding mechanism. The attribute is "close to the water, first to the moon", and it can be used wherever it is declared.

To sum up: dynamic binding mechanism is a function matching mechanism under backflow monitoring. Functions emphasize methods rather than attributes.

🍻 Ending dinner 🍔

Constructor and Getter and Setter in inheritance and encapsulation

🤤 In fact, the purpose of using constructors is to complete an object-oriented parameter transfer and make our classes more diverse and expandable;

 public class Animal{
 private String name;
 //We can see the difference between constructors with parameters and constructors without parameters
 public Animal(String name){ = name;  //Single parameter constructor overrides multi parameter constructor
  public Animal(){ //default constructor 
  public String getName(){
      retrun name;
  public void setName(String name){ = name;
  //In fact, the greater significance is to facilitate the initialization operation when instantiating a class
  //Let's write another Dog class
  class Dog extends Animal{
     public Dog(String name){
         //If we write again at this time = name;
        //In this way, an error will be reported, because you can't break the private defense and directly assign a value to name

Keywords: Java Programming Polymorphism

Added by mY.sweeT.shadoW on Wed, 09 Feb 2022 07:08:35 +0200