Java object oriented (OOP) encapsulation, inheritance, polymorphism, abstract classes, interfaces

Posted by lajocar on Wed, 17 Nov 2021 07:16:39 +0100

Java object oriented (OOP)

  • First knowledge of object-oriented
  • Methods review and deepen
  • Object creation analysis
  • Three characteristics of object oriented
  • Abstract classes and interfaces
  • Internal classes and OOP practice

Procedure oriented... & object oriented

  • Process oriented thought

    • The steps are clear and simple. What to do in the first step, the second part
    • Facing the process, it is suitable to deal with some simpler problems
  • Object oriented thought

    • Birds of a feather flock together, the thinking mode of classification. When thinking about problems, we will first solve what classifications are needed, and then think about these classifications separately. Finally, process oriented thinking is carried out on the details under a certain classification
    • Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation

For describing complex things, in order to grasp them macroscopically and analyze them reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. However, specific to micro operation, it still needs process oriented thinking to deal with it

1. What is object oriented

  • Object oriented programming (OOP)

  • The essence of object-oriented programming is to organize code by class and data by object

  • abstract

    • Pull out the common things

Three characteristics

  • encapsulation
  • inherit
  • polymorphic

From the perspective of epistemology, there are objects before classes. The object is specific food. Class is abstract, which is the abstraction of objects

From the perspective of code operation, there are classes before objects. A class is a template for an object

2. Review method (definition, call)

  • Definition of method

    • Modifier: such as public
    • Return type: the type of return value required by the method
    • The difference between break and return
      • Return: end the method and return the result
      • break: end the loop and jump out of switch
    • Method name
    • Parameter list (parameter type, parameter name)
    • Exception throw
  • Method call

    • The static method keyword static can be clicked through the class name

      • static is loaded with the class
    • Non static methods need to instantiate class (new) before they can be used

    • Formal parameters and arguments: formal parameters: parameters that define methods; arguments: parameters actually passed in

    • this keyword

    • Value passing and reference passing

      Value passing and reference passing

    • package com.oop;
      //pass by value
      public class Demo04 {
          public static void main(String[] args) {
              int a =1 ;
              System.out.println(a);//1
              change(a);
              System.out.println(a);//1
          }
          //The return value is null
          public  static void change(int a){
              a = 10;
          }
      
      }
      
      
    • package com.oop;
      //Reference passing: object, essence or value passing
      public class Demo05 {
          public static void main(String[] args) {
              Person person = new Person();
              System.out.println(person.name);//null
              change(person);
              System.out.println(person.name);//Zhang San
          }
      
          public  static void change(Person person){
              //Person is an object: it refers to a specific person, which can be changed: Person person = new Person();
              person.name = "Zhang San";
          }
      }
      
      //Define a Person class with an attribute: name
      class Person{
          String name ;
      }
      

3. Relationship between class and object

  • Class is an abstract data type. It is the overall description / definition of a class of things, but it can not represent a specific thing

    • Such as: animals, plants, mobile phones, computers
    • Such as: Person class, Pet class, Car class... These classes are used to describe / define the characteristics and behavior of a specific thing
  • Objects are concrete instances of abstract concepts

    • Zhang San is a concrete example of man, and Zhang San's dog is a concrete example
    • What can embody the characteristics and functions is a concrete example, not an abstract concept
//Student class
public class Student {
    //Properties: Fields
    String name ;
    int age ;
    //method
    public void study(){
        System.out.println(this.name+"at school");
    }
}
/**   main
 *         //Class: abstract, instantiated
 *         //An object of its own will be returned after instantiation
 *         //student Object is a concrete instance of the Student class
 *         Student xm = new Student();
 *         Student xh = new Student();
 *         xm.name = "Xiao Ming ";
 *         xm.age = 3;
 *         System.out.println(xm.name);//Xiao Ming
 *         System.out.println(xm.age);//3
 *         xh.name = "Xiaohong ";
 *         xh.age = 3;
 *         System.out.println(xh.name);//Xiao Hong
 *         System.out.println(xh.age);//3
 */

4. Constructor

  • Create an object using the new keyword

  • When using the new keyword, in addition to allocating memory space, the created object will be initialized by default (String=null, int = 0) and the constructor in the class will be called

  • Constructors in classes, also known as constructors, must be called when creating objects.

    • Feature 1: must be the same as the class name
    • 2: There must be no return type and void cannot be written
public class Person {
    //If a class doesn't write anything, it will also have a method
    //Display definition constructor
    String name ;
    int age;
    //1 using the keyword new is essentially calling the constructor
    //2 is used to initialize the value
    public Person(){
        this.name = "Little dream";
    }
    //Parameterized Construction: once a parameterized construction is defined, the definition must be displayed if there is no parameter
    public Person(String name){ //heavy load
        this.name = name;
    }
    //IDEA one click build Constructor Alt+insert - Constructor

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
/* main
        //new Instantiate an object
        Person person =  new Person();//new It is equivalent to calling the constructor
        Person person1 = new Person("name");//Call a parameterless construct (to use a parameterless construct, write a parameterless construct)
        System.out.println(person.name);

        Constructor:
            1 Same as class name
            2 no return value
        effect:
            1 new The essence is to call the constructor
            2 Initializes the value of the object
        be careful:
            1 After defining a parameterized construct, if you want to use a parameterless construct, you need to define a parameterless construct
        IDEA Shortcut key: Alt+Insert
 */

5. Simple analysis of memory diagram

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-mkfe0qxg-163712762279) (tyimage \ image-20211111132218521. PNG)]

  • In the stack
    • Reference variable name: cat - in the referenced Pet class
  • In the pile
    • object
    • Assignment to constant pool
  • Static method area
    • Keyword static: it is loaded together with the class and can be called directly
//Pets
public class Pet {
    public String name ;
    public int age;
    //Nonparametric structure

    //method
    public void shout(){
        System.out.println("call");
    }
}
/*  main
        //new instantiates an object
        Pet dog = new Pet();
        dog.name = "Two dogs";
        dog.age = 3;
        dog.shout();
        System.out.println(dog.age);
        System.out.println(dog.name);
        Pet cat = new Pet();

6. Simple summary

  • Classes and objects
    • Class is an abstract concept, while object is a concrete instance of class
  • method
    • Definition and call
  • Object reference
    • Reference type: basic type (8)
    • Objects are operated by reference: stack - heap
  • attribute
    • Default initialization: Number: 0.0
      • char: u0.000
      • boolean: false
      • Reference: null, such as String
  • Object creation and use
    • You must use the new keyword to create an object, constructor Person p = new Person();
    • Property p.name of object
    • Object's method p.add()
  • Class:
    • Properties: static properties
    • Method: dynamic behavior

7. Encapsulation

  • The dew that should be exposed, the hide that should be hidden
    • We design programs to pursue "high cohesion and high coupling"
      • High cohesion: the internal data operation details of the class are completed by themselves, and external interference is not allowed
      • Low coupling: only a small number of methods are exposed for external use.
  • Encapsulation (data hiding)
    • Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding
  • It's enough to remember this sentence: property private, get/set
/*
    Private properties:
        1. Improve program security and protect data
        2. Hidden code implementation details
        3. Unified interface
        4. Increased system maintainability
 */
public class Student {
    //name
    private  String name;
    //Student number
    private int id;
    //Gender
    private char sex;
    private int age;
    //Provides methods to manipulate these properties
    //Some public get and set methods are provided

//    //Get get data
//    public String getName(){
//
//        return this.name;
//    }
//    //set sets a value for the data
//    public void setName(String name){
//
//        this.name = name ;
//    }
    //Shortcut keys automatically create getter s and setter s
/*
        public static void main(String[] args) {
        Student student = new Student();
        student.setName("Zhang San ");
        System.out.println(student.getName());
        student.setAge(22);
        System.out.println(student.getAge());
    }
 */

8. Inherit

  • The essence of inheritance is to abstract a group of classes, so as to realize better modeling of the real world

  • Extensions · means "extension". A subclass is an extension of a parent class

  • Classes in Java only have single inheritance, not multiple inheritance

  • Inheritance is a kind of relationship between classes. In addition, the relationship between classes includes dependency, composition, aggregation and so on

  • Two classes of inheritance relationship, one is a child class (derived class) and the other is a parent class (base class). The subclass inherits the parent class and uses the keyword extends

  • In a sense, there should be a "is a" relationship between a subclass and a parent class

  • Shortcut keys: Ctrl+H

Parent class:

//Person parent class
public class Person /*extends Object*/ {
    public Person(){
        System.out.println("Person");
    }
    protected String name = "Zhang San";

    public void print(){
        System.out.println("Person");
    }
}

Subclass:

//Student is a subclass of human derived class
//The subclass inherits all the methods of the parent class
public class Student extends Person {
    //Construction method
    public Student(){
        super();//If the parent class constructor is not written, there will be a default
        System.out.println("Student");
    }
    public void print() {
        System.out.println("Student");
    }
    public void test1(){
        print();//print() Student of this method
        this.print();//print() Student of this method
        super.print();//print() Person of parent class
    }
    -----------------------------------------------------------------
        main
        public static void main(String[] args) {
        Student student = new Student();
        output     Person
                Student
    }
}
  • object class
    • All classes in Java inherit the Object class public class Person /*extends Object directly or indirectly by default*/
  • super
      1. When super calls the constructor of the parent class, it must reconstruct the first bit of the method
      2. super must only appear in subclass methods or constructor methods
      3. super and this cannot call constructor at the same time
  • this:
    • The objects represented are different:
      • this: the object itself is the caller
      • super: represents the parent object application
    • premise
      • this: can be used without inheritance
      • super: can only be used under inheritance conditions
    • Construction method
      • this() ; Construction of this class
      • super(); Construction of parent class

Method override (subclass overrides parent method)

  • Method names must be the same
  • Modifier: the scope can be expanded public > protected > Default > private
  • Exception thrown: the scope can be narrowed, but not expanded. Classnotfoundexception > exception is large
  • Rewriting is the rewriting of methods and has nothing to do with properties
  • Shortcut keys Alt+Insert – > override

Why rewrite: the functional subclasses of the parent class do not necessarily need or meet the requirements

Static method

//Parent class
public class B {
    public static void test(){
        System.out.println("BBB");
    }
}
//Subclass
public class A extends B{
    public static void test(){
        System.out.println("AAA");
    }
}
//main
public static void main(String[] args) {
        A a = new A();
        a.test();//AAA
        //The reference of parent class (B) points to child class (A)
        B b = new A();
        b.test();//BBB
    }

Non static method

//Parent class
public class B {
    public  void test(){
        System.out.println("BBB");
    }
}
//Subclass
public class A extends B{
    //Alt+Insert  Override
    //Override override
    @Override //Annotation, functional annotation
    public void test() {
        System.out.println("AAA");
    }
}
//main
/*
	Static methods are very different from non static methods
		Static: method calls are only related to coordinates: a 
		Non static: overriding
*/
public static void main(String[] args) {
        A a = new A();
        a.test();//AAA
        B b = new A();//The subclass overrides the method of the parent class
        b.test();//AAA
    }

b is the object from A new, so the method of A is called

Because static methods are methods of classes, not static methods of objects

When there is static, B calls the method of class B, because B is defined by class B

When there is no static, b calls the method of the object, while b uses class A new

static modified methods are called class members, not object members

A method declared as static cannot be overridden, but can be declared again

9. Polymorphism

  • The same method can adopt a variety of different behavior modes according to different sending objects.

  • The actual type of an object is determined, but there are many types of references that can point to an object

  • Existence conditions of polymorphism

    • Have inheritance relationships (extensions)
    • Subclass overrides parent method
    • A parent class reference points to a child class object
  • Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes

//Parent class----------------------------------
public class Person {
    public void run(){
        System.out.println("Person");
    }
}
//Subclass-----------------------------------
public class Student extends Person{
    @Override
    public void run() {
        System.out.println("Student");
    }
    public void eat(){
        System.out.println("eat");
    }
}
//main----------------------------------
public static void main(String[] args) {
        //The instance type of an object is determined
        //new Student();
        //new Person();

        //The type of reference that can be pointed to is uncertain
        //Subclass - all the methods that students can call are their own or those of the parent class
        Student student = new Student();
        //Parent class - Person can point to subclasses, but cannot call methods unique to subclasses
        Person person = new Student();
        Object ob = new Student();//All classes inherit the object class by default
        person.run();//The subclass overrides the method of the parent class and executes the method of the subclass
        student.run();
//      person.eat();// The methods that can be executed by an object mainly depend on the type on the left side of the object, which has little to do with the right side
        student.eat();
}

1) Polymorphic considerations

  • 1. Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
  • 2. Associated type conversion exception of parent and child classes - ClassCastException
  • 3. Conditions for polymorphism: inheritance relationship, method rewriting, parent class reference pointing to child class object, Father f1 = new Son();

The parent class points to the child class. If the child class does not have a method to execute the parent class, the child class has also been overridden to execute the child class

Which methods cannot be overridden:

  • 1. static method belongs to class, not instance
  • 2. final constant
  • 3. private method (cannot be overridden)

2) instanceof and type conversion

instanceof: you can judge whether the two classes are related

public static void main(String[] args) {
        //Object>Person>Student
        //Object>Person>Teacher
        Object ob = new Student();
        System.out.println(ob instanceof Student);//true
        System.out.println(ob instanceof Person);//true
        System.out.println(ob instanceof Object);//true
        System.out.println(ob instanceof Teacher);//false
        System.out.println(ob instanceof String);//false

        Person ps = new Student();
        System.out.println(ps instanceof Student);//true
        System.out.println(ps instanceof Person);//true
        System.out.println(ps instanceof Object);//true
        System.out.println(ps instanceof Teacher);//false
//        System.out.println(ps instanceof String);// Compilation error

        Student st = new Student();
        System.out.println(st instanceof Student);//true
        System.out.println(st instanceof Person);//true
        System.out.println(st instanceof Object);//true
//        System.out.println(st instanceof Teacher);// Compilation error
//        System.out.println(ps instanceof String);// Compilation error
  • X instanceof Y
    • It can be understood that the reference type on the left and the creation type on the right are connected as a line. All types on the line are of the same type, and those not on the line are not

3) Type conversion

/*	Person Parent class, go();
	Student Subclass, extends Person
*/
		//Type conversion: parent-child
        //High and low
       Person ps = new Student();
        //If you convert the ps object to Student type, you can use Student's method
		//Student st = (Student) ps;
        ((Student) ps).go();
        //When a subclass is converted to a parent class, some of its original methods may be lost
        Student student = new Student();
        student.go();
        Person person = student;
//      person.go();  Cannot call

4) Summary

  • 1. The parent class refers to an object that points to a child class
  • 2. Convert a subclass to a parent class and make an upward Transformation: forced conversion may lose some of the original methods of the subclass
  • 3. Convert a parent class to a child class and transform downward: automatic conversion
  • 4. Facilitate method calls and reduce duplicate code

10. static keyword

  • Static keyword of static method, which can be called directly through the class name
  • Static variable static keyword, which can be called directly through the class name
  • Static variables are shared by all objects (instances) of a class. When called directly by the class, it shows that this variable is static
private static int age; //Static variable multithreading
    private double score;//Non static variable
    public void run(){}//Non static method
    public static void go(){}//Static method
    public static void main(String[] args) {
        Student s1 = new Student();
        //Static variables are shared by all objects (instances) of a class. When called directly by the class, it shows that this variable is static
        System.out.println(s1.score);
        System.out.println(s1.age);
        System.out.println(Student.age);//Class variable
        Student.go();
    }

1) Code block

  • The static code block is executed only once (first)
  • The initial value can be attached before the anonymous code block is constructed and after it is static
 //2
    {
        //Code block (anonymous code block)
        System.out.println("Anonymous code block");
    }
    //1: Execute only once
    static{
        //Static code block
        System.out.println("Static code block");
    }
    //3
    public Person() {
        System.out.println("Construction method");
    }

    public static void main(String[] args) {
        Person person = new Person();
        /*  Output:
            Static code block
            Anonymous code block
            Construction method
         */
        Person person1 = new Person();
        /*  Output:
            Anonymous code block
            Construction method
         */
 }

2) Import static methods of other classes

  • You can use the method directly
//Import static methods of other classes
import static java.lang.Math.random;
public class Test {
    public static void main(String[] args) {
        System.out.println(Math.random());
        //You can use the method directly
        System.out.println(random());
    }
}

11. Abstract class

  • Keyword abstract extends - single inheritance, (interfaces can inherit multiple)
  • Constraint function, only write the method name, no method implementation, and let subclasses complete it
  • be careful:
    • 1. You can't use the abstract class new. You can only rely on subclasses to implement it (if subclasses are also abstract classes, let subclasses complete it)
    • 2. Ordinary methods can be written in abstract classes
    • 3. Abstract methods must be in abstract classes

Think: do abstract classes have constructors?

//Parent class (abstract class)
//Abstract class: Extensions: single inheritance interface - multiple inheritance is allowed
public abstract class Action {
    Action(){
        System.out.println("Action");
    }
    //Constraint ~ someone will help us achieve it
    //Abstract abstract abstract method, only name, no method
    public abstract void doSomething();
}
//Subclass
//All methods of an abstract class that inherit its subclasses must implement its methods unless it is also an abstract class
public class A extends Action{
    A(){
        System.out.println("A");
    }
    @Override
    public void doSomething() {
        System.out.println("AA");
    }

    public static void main(String[] args) {
        A a = new A();//Acton is output and the construction method of the parent class is executed
        a.doSomething();
        /*  Output results
        Action
        A
        AA
         */
    }
}
from A Subclass to complete
//public abstract class A extends Action{
//}
  • new subclass executes the construction method of the abstract class (parent class)

Significance of abstract class existence

  • It can improve development efficiency, because some public relations methods can be written in abstract classes to achieve reuse

12. Interface

  • Common class: only concrete implementation

  • Abstract classes: concrete implementations and specifications (abstract methods) are available

  • Interface: only specification! I can't write my own methods ~ professional constraints, separation of constraints and Implementation: interface oriented programming

  • The keyword for declaring a class is class, and the keyword for declaring an interface is interface

//interface keyword. All interfaces need implementation classes
public interface  UserService {
    //Constant, public static final
    int age = 99;
    //All definitions in the interface are abstract,
    //The default is public abstract
    void add(String name);
    void del(String name);
    void update(String name);
    void query(String name);
}
public interface TimeService {
    void timer();
}
/*
Abstract class: Extensions
 You can implement the implements interface
 If you implement the class of the interface, you need to rewrite the methods in the interface
 */
public class UserServicekImpl implements UserService,TimeService{
    @Override
    public void timer() {}
    @Override
    public void add(String name) {}
    @Override
    public void del(String name) {}
    @Override
    public void update(String name) {}
    @Override
    public void query(String name) {}
}

Function of interface

  • 1. Restraint
  • 2. Define some methods for different people to implement
  • 3. Methods are the default: public abstract
  • 4. Constants are the default: public static final
  • 5. The interface cannot be instantiated. There is no constructor in the interface
  • 6. Implementation can implement multiple interfaces
  • 7. Methods in the interface must be rewritten

13. Inner class

  • Internal class is to define a class inside a class. For example, class B is defined in class A, class B is the internal class of a, and class A is the external class of class B
  • 1. Member inner class
  • 2. Static inner class
  • 3. Local inner class
  • 4. Anonymous inner class
public class Outer {

    private int id = 11;
    public void out(){
        System.out.println("External class");
    }
    public class Inner{
        public void in(){
            System.out.println("Inner class");
        }
        //You can get private information about external classes
        public void getId(){
            System.out.println(id);
        }
    }
    //Static inner class
    public static class A{}

    //Local inner class
    public void method(){
        class B{

        }
    }
}
//There can be multiple class classes in a Java, but there can only be one public class
class A{

}

Topics: Java Back-end