Object oriented core technology (java)

Keywords: Java Programming REST Mobile

1, Class encapsulation details

As mentioned in "java", encapsulation is the core idea of object-oriented programming. At the same time, we also know that classes are carriers, but we encapsulate the properties and behaviors of objects in the carriers.

Now we use the way of encapsulation to realize that a customer goes to a restaurant for dinner and orders a scrambled tomato egg.

Analysis:

  • When a customer goes to a restaurant, he needs to order with the waiter
  • The waiter takes the menu and informs the chef
  • The chef gets the menu and starts to prepare and cook

Note: if the customer tells the waiter what he wants to eat, then the customer can contact the waiter. At the same time, the waiter also records the dishes he wants to eat. Because I want to pass this dish on to the chef. So the chef is always in the back without contact with customers.

//Define restaurant class and provide service for customers
public class Restaurant{
    //Every restaurant has a chef
    private Cook cook = new Cook();
    public static void main(String[] args){
        //Instantiate restaurant and provide service
        Restaurant rest = new Restaurant();
        System.out.println("I'd like to have scrambled eggs with tomatoes. Please help me");
        rest.takeOrder("Scrambled Eggs with Tomato");
    }
    
    //Order for customers
    public void takeOrder(String dish){
        cook.cooking(dish);
        System.out.println(dish + "It's ready to fry. Please enjoy it slowly");
    }
}
​
//Define chef category
class Cook{
    //Chef name
    private String name; 
    public Cook(){
        this.name = "Toni"; 
    }
    //Vegetable washing behavior
    private WashDishes(){
        System.out.println(this.name + "Washing vegetables"); 
    }
    //Fried peanuts
    private void Rice(){
        System.out.println(this.name + "Deep-Fried Peanuts"); 
    }
    //Cooking behavior
    public void Cooking(String dish){
        WashDishes();
        Rice();
        System.out.println(name + "Start frying" + dish);
    }
}

 

In the brief description of encapsulation, the mobile phone class is mentioned. As long as the function users are responsible for using the mobile phone, they don't care how to realize the internal function. As for the restaurant, the customer communicates with the waiter while the chef does not. In other words, customers are only responsible for eating the dishes they have ordered, and they don't know who the chef is, so we can call this process encapsulation.

Extension: Please complete the work by restaurant, user, waiter and chef.

//Restaurants
public class Restaurant3
{
  //Name of restaurant
  public static String name = "Three no real taste private kitchen";
  public static void main(String[] args){
    Restaurant3 rest = new Restaurant3();
    User user = new User();
    Waiter waiter = new Waiter();
    System.out.println("Welcome"+name+","+user.name+",I am"+waiter.name+"serve you");
    System.out.println("What would you like to have?");
    System.out.println("Give me one"+user.SayLive());
    waiter.TakeOrder(user.SayLive());
    //Customers finish eating and check out
    waiter.Cash(user);
    System.out.println(user.name + "Walk slowly");
    System.out.println("How old are you? You look beautiful!");
    waiter.Que();
  }
}
​
//User class
class User
{
  public String name;
  public User(){
    this.name = "Boss";
  }
​
  //Say what you like to eat
  public String SayLive(){
    return "Scrambled Eggs with Tomato";
  }
​
  //Pay
  public void Pay(double money){
    System.out.println("I have paid" + money + ",Make sure.");
  }
}
​
//Attendants
class Waiter
{
  public String name;
  private int age = 19;
  private Cook cook = new Cook();
​
  public Waiter(){
    this.name = "Zhao Min";
  }
​
  //Place an order
  public void TakeOrder(String dish){
    cook.GetOrder(dish);
    System.out.println("The dishes have been fried. Please use them slowly");
  }
​
  //Cash register
  public void Cash(User user){
    System.out.println(user.name+"Hello, 500 yuan in total");
    user.Pay(500.00);
  }
​
  //Asking for fragrant year
  public void Que(){
    System.out.println("Age is not convenient to say");
  }
}
​
//Cooks
class Cook
{
  private String name;
  public Cook(){
    this.name = "Zhou Zhi Luo";
  }
​
  //Washing vegetables
  private void Wash(){
    System.out.println(this.name + "Cleaning vegetables");
  }
  
  //Break the egg
  private void Eggs(){
    System.out.println(this.name + "Breaking eggs");
  }
​
  //Stir fry
  private void cooking(String dish){
    Wash();
    Eggs();
    System.out.println(this.name + "Start cooking" + dish);
  }
​
  //Order sheet
  public void GetOrder(String dish){
    System.out.println("Chef receives customer menu"+dish);
    this.cooking(dish);
  }
}

 

Summary: it is to hide some functions that are only provided for use in the carrier, that is, the class!

2, Class inheritance

The idea of inheritance is that a subclass can inherit the original properties and methods of the parent class, add properties and methods that the parent class does not have, or directly rewrite some methods in the parent class.

Syntax: subclass name extends parent class name

Analysis: inheritance is to let one class inherit another class. You only need to use the extensions keyword. At the same time, note that only one inheritance is supported in java, that is, one class has only one parent class.

Example: inheritance between computer class and tablet

//Computer
class Computer {
    String Color = "black";
    String Screen = "LCD screen";
    void startUp(){
      System.out.println("The computer is turning on, please wait...."); 
    }
}
​
//Tablet PC
public class Pad extends Computer {
  //Tablet's own properties
  String Battery = "10000 Milliampere lithium battery";
  public static void main(String[] args){
    //The parent class instantiates itself
    Computer cp = new Computer();
    System.out.println("Computer The color is" + cp.Color);
    //Computer class object calls power on method
    cp.startUp();
    //Establish Pad Tablet computers
    Pad ipad = new Pad();
    //Call properties of parent class
    System.out.println("ipad The screen of is:"+ipad.Screen);
    //ipad Call your own properties
    System.out.println("ipad Battery:" + ipad.Battery);
    ipad.startUp();
  }
}

 

Analysis: from the above code, we can draw a conclusion that inheritance is only a relationship. Both the parent class and the child class can be instantiated, and the child class object can use the properties and methods of the parent class instead of specific implementation. At the same time, subclasses can also extend their own properties and methods. It is code repeatability that parent class properties and methods are used by subclass objects.

3, Method override

The members of the parent class will be inherited by the child class. When a method of the parent class is not applicable to the child class, the method of the parent class needs to be overridden in the child class.

Implementation of rewriting

Inheritance not only extends the function of the parent class, but also overrides the member methods of the parent class. Rewriting can be understood as covering, that is, keeping the name of the member method of the parent class in the subclass, rewriting the implementation content of the member method of the parent class, changing the storage permission of the member method, or modifying the return data type of the member method.

Conclusion:

  1. Data return type can be overridden
  2. Overriding a method can also increase its parameters
  3. Access permission can only be from small to large, that is, the parent class is private, and the child class can be written as public

Be careful:

The return value, method name, parameter type and number of member methods of subclass and parent are exactly the same. The only difference is the content of method implementation, which can be called refactoring.

//Subclass override parent Eat Method, but also modified the parent class Eat Return type of method
public class Mans extends Humans{
     public String Eat(){
        return "Eating behavior";
     }
     public static void main(String[] args){
        Mans m = new Mans();
        System.out.println(m.Eat());
     }
}
​
//Human beings
class Humans{
    public void Eat(){
        System.out.println("Eating behavior"); 
    }
}

 

 

//Subclass override parent method Eat(),Subclass Eat()Method can receive a parameter
public class Mans extends Humans{
    public void Eat(String name){
         System.out.println("Eating behavior" + name);
    }
  
    public static void main(String[] args){
        Mans m = new Mans();
        m.Eat("Interest!");
    }
}
​
class Humans{
    public void Eat(){
        System.out.println("Eating behavior"); 
    }
}

 

 

//Override parent method Eat(),Overriding is modifying the access rights of the parent class
public class Mans extends Humans{
    public void Eat(){
        System.out.println("Eating behavior"); 
    }
    public static void main(String[] args){
        Mans m = new Mans();
        m.Eat();
    }
}
​
class Humans{
    private void Eat(){
        System.out.println("Eating behavior"); 
    }
}

 

How do subclasses call parent properties and methods

Can't a subclass call a parent's method if it overrides the parent's method? Answer: Yes, you can use the super keyword to call the method of the parent class if you want to call the method of the parent class when the child class overrides the method of the parent class.

In the subclass, the super keyword represents the parent object.

public class Child extends Supers{
    public void Pint(){
        super.Pint();
        System.out.println("I override the method of the parent class"); 
    }
    public static void main(String[] args){
        Supers s = new Supers();
        s.Pint();
    }
}
class Supers{
    public void Pint(){
        System.out.println("I'm the parent method");  
    }
}

 

IV. the parent class of all classes -- Object

All classes in Java directly or indirectly inherit the java.lang.Object class. Also called base class. So the Object class is special because it is the parent class of all classes and the highest level class in Java classes. That is to say, when we create a class, if we do not specify the inheritance class of the class, then the java.leng.Object class is their default inheritance class

public Humans{}  => public Humans extends Object{}

 

Analysis: in the Object class, there are mainly methods such as clone(), finalize(), equals(), toString(). So all classes can override methods in the Object class.

Note: getClass(), notify(), notifyAll(), wait() and other methods in the Object class cannot be overridden, because these methods define the final type, which will be discussed below.

1.getClass() method

The getClass() method will return a Class instance, that is, an object, at the time of execution, and then call the getName() method through the Class instance to get the name of the Class.

//Get the class name of an object
public class Hello{
    public static void main(String[] args){
        Hello h = new Hello(); 
        System.out.println(h); //Hello
    }
  
    public String toString(){
        return getClass().getName(); 
    }
}

 

Conclusion: the combination of getClass() and getName() is to get the class name of the object.

2. The equals () method is used in the Object class to compare whether the reference addresses of two objects are equal.

class H{}
public class Hello{
    public static void main(String[] args){
        String s1 = new String("111");
        String s2 = new String("222");
        System.out.println(s1.equals(s2)); //true
        H h1 = new H();
        H h2 = new H();
        System.out.println(h1.equals(h2)); //false
    }
}

5, Class polymorphism

Polymorphism in a program means that a definition has multiple implementations. For example, there are several "+" in java

Add, sum, and string connector. Class polymorphism can be reflected in two aspects: one is method overloading, the other is class transformation.

5.1 method overload

The name of the constructor is determined by the class name. If you create objects of a class in different ways, you need to use multiple construction methods with different parameters. If there are multiple construction methods in the class, the number of parameters of these construction methods is different, and the method "method overload" must be included. The overload of methods is to allow multiple methods with the same name to exist in the same class at the same time, as long as the parameters or types of these methods are different.

 

public class OverLoadDemo{
    public static int add(int a){
        return a;
    }
  
    public static int add(int a, int b){
        return a + b; 
    }
  
    public static double add(double a, double b){
        return a + b;
    }
    public static int add(int a, double b){
        return (int)(a + b);
    }
  
    public static int add(double a, int b){
        return (int)(a + b);
    }
  
    public static int add(int... a){
        int sum = 0;
        for (int a = 0; i < a.length; i++){
            sum += a[i];
        }
        return sum;
    }
    public static void main(String[] args){
        System.out.println("call add(int)Method:" + add(1));
        System.out.println("call add(int,int)Method:" + add(1,2));
        System.out.println("call add(double,double)Method:" + add(1.5,2.9));
        System.out.println("call add(int,double)Method:" + add(15,2.9));
        System.out.println("call add(double,int)Method:" + add(15.8,9));
        System.out.println("call add(int... a)Method:" + add(1,2,3,4,5,6,7,8,9));
        System.out.println("call add(int... a)Method:" + add(1,2,3,4,5));
    }
}

 

 

 

Note: in a class method, as long as the number or type of parameters of the method is different, and the name of the method is the same, this constitutes an overload

5.2 upward transformation

A subclass refers to an object that is converted to a parent type called an upcast. Generally speaking, it is to turn a subclass object into a parent object. Where the parent object can also be an interface.

class Parent
{
  public static void draw(Parent p){
    System.out.println("I'm starting to come");
  }
}
​
public class Zhuangxing extends Parent
{
  public static void main(String[] args){
    Zhuangxing zx = new Zhuangxing();
    zx.draw(zx);
}

 

Parent is our parent class of Zhuangxing. There is a draw() in the parent class with a parameter. The type of this parameter is parent, that is, the parent class itself. In the main method of Zhuangxing class, we get the subclass object and call the draw() method of the parent class. At the same time, we pass the subclass object as a parameter into the draw() method. Because parent class and Zhuangxing are inheritance relations, when assigning subclass objects to parent type objects, we call them upward transformation.

class Parent{
  public static void hello(){
    System.out.println("Hello");
  }
}
public class Zhuangxing extends Parent{
  public String name = "Zhang San";
  public static void main(String[] args){
    //Upward transformation is a subclass object as a parent object
    //Zhuangxing zx = new Parent(); This is wrong
    Parent p = new Zhuangxing(); //Treat subclass object as parent
    p.name; //Error reported, unable to find this method
  }
}

 

Analysis:

When transitioning up, objects of the parent class cannot call properties or methods unique to the child class. It is possible for our parent class object to call its own properties or methods. This is actually a feature of the upward transformation. The objects in the upward transformation will lose the methods that the parent class does not have, and the methods with the same name of the child class will overwrite the methods with the same name of the parent class. Equivalent to upward transformation, the modified object is inaccessible to methods that only exist in the subclass but not in the parent class. At the same time, if the subclass overrides some methods of the parent class, when calling these methods, it actually calls the methods defined by the subclass, that is, dynamic linking and dynamic calling. Generally speaking, an apple can be a fruit, but it can't be said that a fruit is an apple. If you want fruit to call Apple's unique properties and methods, this is not reasonable.

class Fruit //Fruits
{
  public void sayName(){
    System.out.println("I am fruit.");
  }
}
public class Apple extends Fruit //Apple class and inherit fruit class
{
  public static void main(String[] args){
    //Upward transformation
    Fruit apple = new Apple();
    apple.sayName();
    apple.Hello(); //There will be an error here, saying there is no such way
  }
  
  //This is a unique way for Apple
  public void Hello(){
    System.out.println("I'm the apple way");
  }
​
  public void sayName(){
    System.out.println("I am apple....");
  }
}

 

Summary: the upward transformation is to extend the method of the parent class object, that is, the parent class object can access the method of the child class object overriding the parent class.

5.3 downward transformation

Downward transformation refers to the transformation of the object of the parent type into the child type. That is, a subclass type is declared, but an object of the parent type is referenced.

At the same time, the upward transformation can be done automatically by the java compiler, but the downward transformation requires manual coercion.

class Fruit{
    public void sayName(){
        System.out.println("I am fruit."); 
    }
}
​
public class Apple extends Fruit{
    public void sayName(){
        System.out.println("I am apple."); 
    }
    
    //Subclass unique methods
    public void Hello(){
        System.out.println("I'm a subclass only method"); 
    }
  
    public static void main(String[] args){
        Fruit apple = new Apple(); //A parent type references a child object
        apple.sayName(); //The output is  - I am apple.
        
        //Forced rebroadcast->Parent class Fruit Object apple Transition down to subclass type Apple
        Apple fruit = (Apple)apple;
        fruit.sayName(); //I am apple.
        fruit.Hello(); //No mistake.->Output I'm a subclass specific method content
    }
}

 

Analysis:

First, Apple's type is fruit class, but it actually refers to an instance of the subclass apple, so apple is transforming fruit type upward. From the code point of view, apple is the parent type (fruit), which refers to the child object. So it is safe to convert apple from fruit type down to Apple type. Because our apple object itself points to subclass objects.

Note: about loading in the up-down transformation

Whether up or down, classes are loaded into memory when they are loaded. However, during the upward transformation, although the object has lost the method with the same name as its parent class, these methods have been loaded into memory. Because of the upward transformation, the object cannot call these methods. At the same time, the class will be loaded, except that the object specific properties will not be loaded.

Summary of upward and downward transformation

  1. Upward and downward transformation is a mechanism to realize polymorphism
  2. The purpose of up conversion compiler is to abstract objects and simplify programming
  3. In the upward transformation, the subclass will lose the method with the same name of the parent class, and the method with the same name of the subclass will overwrite the method of the parent class
  4. Downward transformation needs compulsory transformation
  5. In the downward transformation, attention should be paid to whether the object refers to a subclass object or a parent object. When referring to a subclass object, an error will not be reported. When referring to a parent class, an error will be reported

The secret of java Abstract Programming is to transform up and down at the same time. Upward transformation is a mechanism to achieve polymorphism. We can perform corresponding actions through the dynamic allocation mechanism provided by polymorphism. Code written with polymorphism is easier to expand and maintain without using multiple types of detection code.

5.4 instanceof keyword

class Fruit{
    public void sayName(){
        System.out.println("I am fruit."); 
    }
}
public class Apple extends Fruit{
    public static void main(String[] args){
        //fruit Is the parent type reference pointing to or parent type
        Fruit fruit = new Fruit();
        //Fruit Type fruit Downward forced transition to Apple type
        Apple apple = (Apple)fruit;
        apple.sayName();
    }
    public void sayName(){
        System.out.println("I am apple."); 
    }
}

 

Code compilation environment will not report errors, but running code will package java.lang.ClassCastException: Fruit cannot be cast to Apple errors. This is also the scene we will encounter when we start to learn transformation.

Object A instanceof class B = > translation is: whether object A is an instance of class B, if it returns true, otherwise it is false

 

class Fruit{
    public void sayName(){
        System.out.println("I am fruit."); 
    }
}
public class Apple extends Fruit{
    public static void main(String[] args){
        Fruit apple = new Apple(); // Downward transformation
        Apple fruit = null;
        //judge apple Is it right? Apple Example
        if (apple instanceof Apple){
            fruit = (Apple)apple;
        }
        fruit.sayName(); //I am apple.
        fruit.Hello();//I'm a subclass only method
    }
    public void sayName(){
        System.out.println("I am apple.");
    }
    public void Hello(){
        System.out.println("I'm a subclass only method"); 
    }
}

Posted by andycastle on Tue, 14 Apr 2020 04:44:16 -0700