java object oriented (OOP)

java object oriented (OOP)

Process oriented & object oriented

  • Process oriented
    • What's the first step? What's the second step
    • Micromanipulation
  • object-oriented
    • Classified thinking
    • It is suitable for dealing with complex and multi person collaborative problems

For describing complex things, in order to grasp them from the macro and analyze them reasonably as a whole, it is necessary to analyze the whole system object-oriented

However, when it comes to micro operation, it still needs to be process oriented

object-oriented

  • Object-Oriented Programming, OOP

  • Essence: organize code in the form of class and encapsulate data in the form of object

  • characteristic

    • encapsulation

    • inherit

    • polymorphic

encapsulation

  • High cohesion: hide the properties and implementation details of the object, and only expose the interface to the public
  • Property is private, which is obtained through get and set
  • Inside the get and set methods, you can perform some legitimacy checks (for example, the age cannot be 999) to avoid the risk of direct modification

inherit

Modifier

  1. extends

    1. In Java, if you do not explicitly write the extends class, the compiler will automatically add the extends Object
    2. Java allows only one class to inherit from one class, so a class has and only has one parent class. Only Object is special. It has no parent class
  2. protected

    1. Subclasses cannot access the private field or private method of the parent class
    2. Protected keyword can control the access rights of fields and methods within the inheritance tree. A protected field and method can be accessed by its subclasses and subclasses of subclasses
    3. Four priorities: public, protected, default, private
  3. final

    1. In general, as long as a class does not have a final modifier, any class can inherit from that class.

Construction method

  1. Incoming parameters, direct initialization

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
  2. Super keyword indicates the parent class (superclass). When a subclass references a field of a parent class, you can use super fieldName.

    class Person {
    	//attribute
        private String name;
        private int age;
    	//initialization
        public Person(String name, int age) {
        	super();//Call the parent class constructor
            this.name = name;
            this.age = age;
        }
        //method
        public String getName() {
            return this.name;
        }
    
        public int getAge() {
            return this.age;
        }
    }
    
  3. Construction sequence

    public class Person{
        public Person{
            System.out.println("Parent class construction");
        }
    }
    
    public class Student extends Person{
        public Student{
            System.out.println("Subclass construction");
        }
    }
    
    public class Test{
        public static void main(String[] args){
        	Student student = new Student();
    	}
    }
    
    /*output
    	Parent class construction
    	Subclass construction
    */
    

    The parent class is constructed first, and then the child class is constructed

Upward transformation and downward transformation

  1. Upward transformation

    1. The reference of the parent class points to the child class

      Reference type is a structure that organizes data and functions together, also known as object definition. It describes the attributes and methods of its own object.

      Meng Xin's simple understanding: the stack contains a reference to the Person type, but the heap it points to contains the Student type

      Person p = new Student();
      
    2. Method overridden * (or method overridden)*

      class A {
          public void print() {
              System.out.println("A:print");
          }
      }
      
      class B extends A {
          public void print() {
              System.out.println("B:print");
          }
      }
      
      public class Hello {
          public static void main(String args[])
          {
              A a = new B();
              a.print();
          }
          
          //B:print
      

      The method that loses a subclass is transformed upward, but the subclass method is effective after the subclass override s the parent method

      Originally, the methods of the subclass should be lost, but because the parent class also has this method, the methods of the subclass override the methods of the parent class

      If there is a parent class, it will be overwritten

      If there is no parent class, it will be lost

      Static methods are not overridden and therefore not overridden

      class A {
          public static void print() {
              System.out.println("A");
          }
      }
      
      class B extends A {
          public static void print() {
              System.out.println("B");
          }
      }
      
      public class Test {
          public static void main(String args[])
          {
              A a = new B();
              a.print();
          }
          
          //A
      

      Method can be overridden, property cannot be overridden. The methods of the parent class are overwritten by the child class, and the properties of the parent class are not overwritten by the child class.

      public class Son extends Father {
      	public String name = "Subclass properties";
       
      	public void show() {
      		System.out.println("Subclass method");
      	}
      	
      	public static void main(String[] args) {
      		Father son = new Son();
      		son.show();
      		System.out.println(son.name);
      	}
      }
       
      class Father {
      	public String name = "Parent class attribute";
       
      	public void show() {
      		System.out.println("Parent method");
      	}
      }
          
          /*Output:
          	Subclass method
          	Parent class attribute
          */
      
    3. effect

      Reduce duplicate codes and pass in parameters

      public class Test {
          public static void main(String[] args) {
              A(new Daughter());//Can be regarded as father daught = new daught();
              A(new Son());//Can be regarded as Father son = new Son();
          }
          public static void A(Father children){
              children.eat();
          }
      }
      
  2. Downward transformation

    1. The parent class is cast into a subclass to call the unique methods of the subclass (rarely used in Engineering)

    2. instanceof: judge whether an object is an instance of a class

      A a = new B();                 //Upward transformation (class B is A subclass of class A)
      
      a instanceof A;                //Return true
      a instanceof B;                //Return true
      a instanceof C;                //Return false
      
    3. The parameter is transferred upward, and instanceof can distinguish which subclass it is

      class A {
               public void print() {
                        System.out.println("A:print");
               }
      }
      
      class B extends A {
               public void print() {        
                        System.out.println("B:print");
               }
               public void funcB(){
                        System.out.println("funcB");
               }
      }
      
      class C extends A {
               public void print() {        
                        System.out.println("C:print");
               }
               public void funcC(){
                        System.out.println("funcC");
               }
      }
      
      public class Test{
               public static void func(A a)
               {
                        a.print();
                        if(a instanceof B)
                        {
                                B b = (B)a;   //Downward transformation, instantiating subclasses through parent classes
                                b.funcB();    //Call methods unique to class B
                        }
                        else if(a instanceof C)
                        {
                                C c = (C)a;  //Downward transformation, instantiating subclasses through parent classes
                                c.funcC();   //Call methods unique to class C
                        }
               }
      
               public static void main(String args[])
               {
                        func(new A());   
                        func(new B());
                        func(new C());
               }
      }
      
  3. Override and overload override

    Overrides are only available to subclasses and superclasses: subclasses override the methods of the parent class (for methods, properties cannot be overridden. Therefore, the properties of the parent class will not be overwritten)

    1. Difference: the parameter list must be the same, or it will become overloaded

    2. Modifier: the scope may be expanded, but cannot be reduced. Public > protected > Default > private

    3. Exception thrown: the range can be reduced, but not increased. Classnotfoundexception -- > exception (large)

    4. **Overriding override means overriding the previous method The previous method cannot be used and has been overwritten**

      overload is the reuse of methods Overloaded methods and previous methods can be used

polymorphic

  • Polymorphic based on override

  • It is allowed to add more types of subclasses to realize function expansion without modifying the code based on the parent class.

  • Function expansion based on rewriting override

    I don't know whether the actual parameter type passed in is Person or a subclass of Person

    public void runTwice(Person p) {
        p.run();
    }
    
  • The parent class uses polymorphism to derive subclasses and override the corresponding methods

    See the following abstract classes for examples of polymorphic usage

other

  1. static

    1. Static properties and methods can be called through classes

      During class loading, static variables, static methods and constants are stored in the method area

    2. Anonymous and static blocks

      public class Person{
          {
              System.out.println("Anonymous code block");
          }
          static{
              System.out.println("Static code block");
          }
          public Person(){
              System.out.println("Construction method");
          }
          public static void main(String[] args){
              Person person1 = new Person();
              System.out.println("=============");
              Person person2 = new Person();
          }
      }
      /*output
      	Static code block
      	Anonymous code block
      	Construction method
      	=============
      	Anonymous code block
      	Construction method
      */
      

      Static code blocks are executed only once

      Anonymous code block executed each time: used to assign initial value

  2. import

    1. In order to make the method with the same name, the variable can be distinguished and put it into different package s

      When using these methods and variables, you need to enter the full name: package name Method name

      However, when import ing the classes in the package, you can directly enter the corresponding method name without entering the package name In this way, there is no need to write long names, which is very convenient

    2. Two import methods

      Import a class in the sub package: import Java util. ArrayList;

      Import all classes in the sub package: import Java util.*; (import declaration on demand)

      Generally, large projects do not need to be imported on demand

      Because: slow compilation, naming conflicts, poor readability, nameless package problems

    3. import static

      import imports classes and interfaces, but variables and methods in classes can only be imported statically (because it must be attached to a class or interface)

      //Directly import specific static variables, constants and methods. Note that the import method directly writes the method name without parentheses.
      import static java.lang.Math.random;//method
      import static java.lang.Math.PI;//attribute
      import static java.lang.Math.*;//Import on demand
      

Abstract classes and interfaces

abstract class

First, we need to understand what abstraction is

abstract English has the meaning of simplification That is, abstraction is to compress and simplify a lot of information

For example, a student class has the following attributes: student number, name, gender, date of birth

However, in addition to these, there must be physical attributes such as tall, short, fat, thin, beautiful and ugly, and family attributes such as parents living or both dead

Because we don't need this information, we didn't write the student class

We remove a lot of information and simplify it. The process of abstract is abstraction

What is an abstract class?

An abstract class is the abstraction of a class

For example, there are many kinds of dogs, such as shepherd, wood dog, Labrador, Bomei, etc

The subdivisions of these dogs, such as sheepdog, will be abstracted as "dog" These classes will inherit from the dog class That is, their inherent commonness is "dog"

This "dog" class is an abstract class

  • characteristic

    • abstract modification

    • It contains abstract methods, but it can also contain ordinary member methods and member variables

      abstract void fun();
      

      Abstract method: only declaration, no concrete implementation

      Abstract method must be public or protected By default, the default is public

    • Abstract classes cannot be instantiated.

    • Abstract methods in an abstract class must be implemented by subclasses. If subclasses cannot be implemented, then subclasses must also be abstract classes.

  • use

    [public] abstract class ClassName {
        abstract void fun();
    }
    
    • Abstract classes are mainly used for inheritance

      After being inherited, the subclass will override the abstract methods in the abstract class, which can be implemented according to the different needs of the subclass

      For example:

      Abstract class flying object class has abstract method abstract void fly() Aircraft and birds can inherit flying objects

      Aircraft and birds have different flight modes, which can be rewritten and implemented according to their respective flight modes

Interface

What is an interface?

Abstract classes exist because of inheritance and pass everything on to subclasses

Interfaces exist for attachment, to attach something to a class

One is total acceptance, the other is additional

For example, doors open and close This is the inherent property of the door itself (abstract class)

But some doors can give an alarm and some doors can be unlocked with a password (Interface)

We can add these interfaces to some doors

But not all doors must have an alarm system and unlock with a password It's just an additional act

Interface is a specification and a rule that everyone abides by.

Just like the law, if everyone abides by it, we can be prosperous, strong, democratic, civilized and harmonious together.

  • characteristic

    • interface modification

    • Interfaces can contain variables and methods. (but variables are generally not defined in the interface)

    • The variables in the interface will be implicitly specified as public static final variables (and they can only be public static final variables, which will report compilation errors if decorated with private)

      The method will be implicitly specified as a public abstract method and can only be a public abstract method (modification with other keywords, such as private, protected, static, final, etc., will report compilation errors)

    • All methods in the interface cannot have concrete implementation, that is, the methods in the interface must be abstract methods.

      All methods in the interface must also be implemented by subclasses. If subclasses cannot be implemented, then subclasses must be abstract classes.

    • A class can implement multiple interfaces

  • use

    [public] interface InterfaceName {
    	
    }
    
    • The keyword implements is needed to implement an interface. It says: "my class follows the protocol of the interface. If you want to use me, just look at the interface. Don't care about the specific implementation."

      class ClassName implements Interface1,Interface2,[....]{
          
      }
      
    • Like the upward transformation of abstract classes, classes that implement interfaces can also be transformed upward into interfaces

      interface A {
      	void func();
      }
      
      class B implements A {
      	@Override
      	public void func() {
      		System.out.println("func");
      	}
      }
      
      public class Test {
      	public static void func(A a) {
      		a.func();
      	}
      	
      	public static void main(String[] args) {
      		B b = new B();
      		func(b);
      	}
      }
      
    • Adapter mode of interface

      • Adapter mode: transfer the original interface according to the needs of the caller.

        If the class implements the interface directly, it needs to implement two methods.

        If we only need to implement one of these methods, we can use an abstract class as the middleware, that is, adapter coach.

        Use this abstract class to implement the interface and empty the method in the abstract class (the method body has only a pair of curly braces because the method is a non abstract method).

        At this time, the new class can bypass the interface and inherit the abstract class, so we can only cover the required methods, not all the methods in the interface.

difference

  • Prohibit multiple inheritance

    When inheriting multiple parent classes, these parent classes have different methods with the same name, which will cause ambiguity (there are other reasons, which can be simply understood here)

    java prohibits multiple inheritance, but introduces interface The interface can implement more than one, which makes up for the defect of not inheriting more

  • Inherent and additional (innate and acquired)

    Abstract class is the overall abstraction of subclasses, a kind of template design It is innate and inherent in itself

    Interfaces are extended additional behaviors, acquired and additional attributes

    The interface is widely used Such as alarm device, it can be used in door, indoor, mobile phone, car

  • modify

    Abstract classes can be modified directly without changing subclasses

    If the interface is updated, each class implementing the interface needs to be changed

  • Design

    The design purpose of the interface is to restrict the behavior of classes (more accurately, it is a "yes" constraint, because the interface cannot specify what behavior classes cannot have), that is, to provide a mechanism that can force different classes to have the same behavior. It only restricts whether the behavior exists or not, but does not limit how to realize the behavior. For the understanding of "why interfaces are constraints", I think it is better to cooperate with generics.

    The design purpose of abstract classes is code reuse. When different classes have some of the same behaviors (recorded as behavior set A) and some of the behaviors are implemented in the same way (non true subset of a, recorded as b), these classes can be derived from an abstract class. B is implemented in this abstract class to avoid all subclasses realizing B, which achieves the purpose of code reuse. The part of a minus B is left to each subclass to implement. It is precisely because A-B is not implemented here that abstract classes are not allowed to be instantiated (otherwise, they cannot be executed when called to a-b).

  • Grammatical level

    1. Abstract classes can provide the implementation details of member methods, and only public abstract methods can exist in the interface;

    2. Member variables in abstract classes can be of various types, while member variables in interfaces can only be of public static final type;

    3. Interfaces cannot contain static code blocks and static methods, while abstract classes can have static code blocks and static methods;

    4. A class can only inherit one abstract class, while a class can implement multiple interfaces.

reference material:

java up transformation, down transformation

What is generics

import

Deep understanding of Java interfaces and abstract classes

java abstract classes and interfaces. It's enough to read this article

What is the difference between an interface and an abstract class

The difference between abstract classes and interfaces

Tags: Java encapsulation abstract class Polymorphism

Posted by jmrouleau on Mon, 18 Apr 2022 03:51:15 +0930