Java Core Concepts Object-Oriented Programming OOP

  • kind

    • It is a template, which is used to define the methods and attributes of a class of objects, such as people, students, animals, and cats. Everything has a template and can be defined as a class.
    • Capitalize the first letter of the class name
      class Person {
      
      }
      
  • object

    • The instantiation of a class, for example, the instantiation of the student class is student XX
      Person person = new Person();
      new Persion();
      
  • method

    • A method is a collection of statements that together complete a function
    • Methods are contained in classes or objects, that is, ordinary methods or class methods
      Modifier Return value type Method name(Parameter type Parameter name) {
          ...
          method body
          ...
          return return value;
      }
      
  • inherit

    • The subclass inherits the characteristics and behaviors of the parent class, so that the subclass object has the methods and attributes of the parent class.
    • The parent class is also called the base class and has public methods and properties.
  • Polymorphism

    • The ability to have multiple different manifestations of the same behavior
    • Advantages: reduced coupling, flexible and scalable
    • Generally, it is implemented by inheriting a class or overriding a method.
  • abstract

    • The class declared by keyword abstract is called abstract class, and the method declared by abstract is called abstract method.
    • If a class contains one or more abstract methods, the class must be designated as an abstract class.
    • An abstract method is a special method that contains only one declaration and no method body.

Constructor and method encapsulation in Java object-oriented

  • What is a constructor

    • A special method used to initialize the object when creating it. Every time new is used to create an object, the constructor is used.
    • With the same name as the class, but no return value, Java automatically provides a default constructor for each class
    • If you define a constructor yourself, the default constructor will no longer be used. If the default constructor is not written explicitly, it will disappear.
    • Note: If constructors call each other, they must be written in the first line of the method.
  • Constructor type

    • Default constructor (also called parameterless constructor)
      public Class name() {
      
      }
      
    • No-argument constructor
      public Class name() {
      
      }
      
    • Parametric constructor
      public Class name(Parameter type1  Parameter name1, Parameter type2 Parameter name2...) {
      
      }
      
  • Constructor modifiers

    • Public is most commonly used to create objects.
    • private private constructor, does not create external objects, such as tool classes, or singleton design patterns
    • default By default, you can only use new to create objects in the current package, which is almost never used.
  • encapsulation

    • Encapsulation is to surround the process and data. Access to the data can only be through defined interfaces or methods.
    • Encapsulation is achieved in java through the keywords private, protected and public.
    • What is encapsulation? Encapsulation combines all the components of an object and defines how programs refer to the object's data.
    • Encapsulation actually uses methods to hide the data of a class and control the extent to which users can modify the class and access the data.
    • Proper encapsulation can make the code easier to understand and maintain, and also enhance the security of the code.
    • include:Class encapsulation, method encapsulation
  • overload (overload, overload)

    • In a class, the method names are the same but the parameters are different, regardless of the return type.
    • Method names must be the same.
    • Parameter lists must be different (parameter type, number of parameters, parameter order).
    • The return types of methods can be the same or different.
    • Overloading has nothing to do with the access modifier of the method and whether it is static.
      // no parameter method
      public void display() {
          System.out.println("Display method with no parameters.");
      }
      
      // method with an integer parameter
      public void display(int num) {
          System.out.println("Display method with int parameter: " + num);
      }
      
      // Method with a string parameter
      public void display(String str) {
          System.out.println("Display method with String parameter: " + str);
      }
      
  • override (rewrite, cover)

    • The subclass rewrites the implementation process of the parent class's methods that allow access, and neither the return value nor the formal parameters can be changed.
    • include:Return value type, method name, parameter type and number
    • Subclasses can implement the methods of the parent class as needed
      // override(rewrite, overwrite)
      @Override
      public void makeSound() {
          System.out.println("Meow");
      }
      

Java object-oriented core keyword this

  • this keyword

    • In Java,thisis a special reference variable that refers to the current object itself.
    • Inside the class you can usethisto reference the variables and methods of the current instance of the object.
    • thisThe main uses of keywords are:
      • Distinguish between member variables and local variables
      • Reference other constructors in the constructor bythis()
  • Things to note

    • thisCannot be used in static methods because static methods do not belong to any instance of the class.
    • thisThe reference is to the memory address of the current object, not its value.
    • thisIt can only be used in constructors or instance methods, not in class methods (static methods).
    • If not explicitly used in the constructorthisTo call another constructor, the parameterless constructor (if it exists) will be automatically called.
    • But if it has been used in the constructorthis()To call another constructor, you cannot call another constructor or the default constructor.
  • example:

    public class ThisExample {
        private int x, y;
    
        public ThisExample(int x) {
            this(x, 0);
        }
    
        public ThisExample(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        public void printXY() {
            System.out.println("x: " + x + ", y: " + y);
        }
    
        public static void main(String[] args) {
            ThisExample thisExample = new ThisExample(1);
            thisExample.printXY();
        }
    }
    

Inheritance in object-oriented programmingextend

  • inherit

    • The subclass inherits the characteristics and behaviors of the parent class, so that the subclass object has the methods and attributes of the parent class.
    • The parent class is also called the base class and hasPublic methods and properties, examples in life
    • Inheritance in java to reduce duplicate code
  • Format, through the extends keyword

    class Parent class name {
        
    }
    
    class Subclass name extends Parent class name {
        
    }
    
  • Features

    • The subclass has the parent class'sNon-private properties and methods
    • Subclasses can implement the methods of the parent class in their own way override (rewrite, cover)
    • It realizes the reuse of code and overrides the methods inherited from the parent class. When calling the method, the method of the subclass will be called first (default proximity principle)
  • Constructors and inheritance

    • Subclasses cannot inherit the constructor of the parent class, but the subclass will automatically call the constructor of the parent class when creating an object (if the parent class has a default constructor).
    • If the parent class does not have a parameterless constructor, and the subclass constructor does not explicitly call the parent class's constructor, a compilation error will occur.
    • Subclasses can passsuper()keyword explicitly calls the constructor of the parent class, andsuper()The call must be on the first line of the subclass constructor.
  • Notice

    • Multiple inheritance is not supported, but multiple inheritance is supported. Multiple inheritance improves coupling, and combination is better than inheritance.
    • All classes inherit from java.lang.Object
    • final keyword
      • Modified class, this class cannot be inherited
      • Modified method, this method is not allowed to be overridden (overridden)

Inherited super keyword in Java object-oriented programming

  • super keyword

    • A reference variable used to refer to the parent class object
    • Both the parent class and the subclass have the same naming method, which is used when calling the parent class method.
    • Both the parent class and the child class have the same named properties, which are used when calling properties in the parent class
    • super is also the constructor of the parent class, format super (parameter)
      • Note: calling super() must be the first statement in the class constructor, otherwise the compilation will not pass.
  • Notice

    • The first statement of each subclass constructor implicitly calls super(). If the parent class does not have a constructor in this form, an error will be reported during compilation.
      public class Animal {
          public Animal() {
              System.out.println("AnimalNo-argument constructor");
          }
      }
      
      public class Cat extends Animal {
          public Cat() {
              // super();
              System.out.println("CatNo-argument constructor");
          }
      }
      
    • This() and super() both refer to objects and cannot be used in a static environment.
      • Including: static variables, static methods, static statement blocks.
  • super and this in the constructor

    • There can only be one this and super in the constructor, and both must be the first line in the constructor.
    • When the constructor of the parent class is a no-argument constructor, in the constructor of the subclass, there is no need to explicitly call super() to call the constructor of the parent class.
    • When the constructor of the parent class is a parameterized constructor, if super() is not written in the constructor of the subclass to call the constructor of the parent class, the compiler will report an error.
  • Initialization order of classes after java inheritance

    • Static code block, non-static code, parent class/child class no-argument construction method, general method of parent class/child class
  • example:

    public class Animal {
        static {
            System.out.println("Animalstatic code block");
        }
    
        // Default constructor (no-argument constructor)
        public Animal() {
            System.out.println("AnimalNo-argument constructor");
        }
    
        // Parametric constructor
        public Animal(String name) {
            this.name = name;
        }
    
        // Parametric constructor
        public Animal(int age) {
            this.age = age;
        }
    
        // Parametric constructor
        public Animal(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        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;
        }
    
        public void eat() {
            System.out.println("Have a meal");
        }
    
        public void sleep() {
            System.out.println("sleep");
        }
    
        public void makeSound() {
            System.out.println("Call");
        }
    }
    
    public class Cat extends Animal {
        static {
            System.out.println("Catstatic code block");
        }
    
        public Cat() {
    //        super();
            System.out.println("CatNo-argument constructor");
        }
    
        public Cat(String name) {
            super(name);
        }
    
        public Cat(int age) {
            super(age);
        }
    
        public Cat(String name, int age) {
            super(name, age);
        }
    
        public void catchMice() {
            System.out.println("catch mice");
        }
    
        // override(rewrite, overwrite)
        @Override
        public void makeSound() {
            System.out.println("Meow");
        }
    }
    
    public class ExtendDemo {
        public static void main(String[] args) {
            Cat cat1 = new Cat();
            Cat cat2 = new Cat("Dundun", 2);
            System.out.println(cat2.getName());
            System.out.println(cat2.getAge());
            cat2.eat();
            cat2.sleep();
            cat2.catchMice();
        }
    }
    
    Animalstatic code block
    Catstatic code block
    AnimalNo-argument constructor
    CatNo-argument constructor
    Dundun
    2
    Have a meal
    sleep
    catch mice
    

Java object-oriented programming abstract abstract

  • abstract

    • When some methods of the parent class are uncertain, you can use the abstract keyword to modify the method, that is, abstract method, and use abstract to modify the class, that is, abstract class
    • Abstract classes extract the common features of things and implement them through inheritance by subclasses. The code is easy to expand and maintain.
    • Abstract classes and abstract methods in java
  • Abstract features:

    • Characteristics of abstract classes
      • Abstract classes cannot be instantiated because the methods in the abstract class are not concrete. This is an incomplete class, so it cannot be instantiated directly and compilation cannot pass.
      • An abstract class does not necessarily contain abstract methods, but a class with abstract methods must be an abstract class
      • If there can be no abstract methods in an abstract class, the purpose of this is so that this class cannot be instantiated.
      • The subclass of an abstract class must give a specific implementation of the abstract method in the abstract class, otherwise the subclass is also an abstract class and needs to be declared with abstract
      • Abstract classes cannot be modified with the final keyword because final-modified classes cannot be inherited.
    • Characteristics of abstract methods
      • Abstract methods in abstract classes are just declarations and do not contain method bodies.
      • Abstract methods cannot be modified with private, because abstract methods must be implemented (overridden) by subclasses, and private permissions are not accessible to subclasses.
      • If a class inherits an abstract class, it must override all abstract methods in the abstract class. Of course, it does not need to override all of them.
      • If you do not override all abstract methods, this subclass must also be an abstract class.
    • Constructors and class methods (i.e. static modified methods) cannot be declared as abstract methods
  • example:

    // abstract class
    abstract class Vehicle {
        // abstract method
        public abstract void start();
    
        public void stop() {
            System.out.println("stop running");
        }
    }
    
    class Car extends Vehicle {
        @Override
        public void start() {
            System.out.println("car running");
        }
    }
    
    public class AbstractDemo {
        public static void main(String[] args) {
            Vehicle car = new Car();
            car.start();
            car.stop();
        }
    }
    

[New Features] Java object-oriented programming interface interface

  • interface

    • It is a collection of abstract methods. An interface is usually declared as interface. A class inherits the abstract methods of the interface by inheriting the interface.
    • Java 8 and later can also include default methods and static methods, but do not include method implementations.
    • effect
      • decoupling: Interface defines the contract between objects, making the interaction between different classes clearer and more flexible.
      • multiple inheritance: By implementing multiple interfaces, a class can inherit methods in multiple interfaces to achieve functions similar to multiple inheritance.
      • Definition specification: An interface defines a set of methods. Classes that implement the interface must follow the definition of these methods.
  • Interface definition

    • Interface usageinterfaceTo define, the methods in the interface are implicitly abstract (no need toabstractkeyword), and bothpublicof (not explicitly specified).

      public interface MyInterface {
          // Constant definition, the default ispublic static finalof
          int CONSTANT = 0;
      
          // Abstract method definition, the default ispublicof
          void method();
      
          // Java 8and later, interfaces can contain static methods
          static void staticMethod() {
              System.out.println("MyInterfacestatic method");
          }
      
          // Java 8and later, interfaces can contain static methods
          default void defaultMethod() {
              System.out.println("MyInterfaceThe default method of");
          }
      }
      
  • Interface implementation

    • class can be usedimplementskeyword to implement one or more interfaces
    • If a class implements an interface, it must implement all abstract methods in the interface, except default methods and static methods.
      public class MyClass implements MyInterface {
          @Override
          public void method() {
              System.out.println("MyClassmethod");
          }
      }
      
  • example:

    public interface Shape {
        void draw();
    
        void calculateArea();
    }
    
    public class Circle implements Shape {
        @Override
        public void draw() {
            System.out.println("draw a circle");
        }
    
        @Override
        public void calculateArea() {
            System.out.println("Calculate the area of ​​a circle");
        }
    }
    
    public class Rectangle implements Shape {
        @Override
        public void draw() {
            System.out.println("draw rectangle");
        }
    
        @Override
        public void calculateArea() {
            System.out.println("Calculate the area of ​​a rectangle");
        }
    }
    
    public class InterfaceDemo {
        public static void main(String[] args) {
            MyInterface myClass = new MyClass();
            myClass.method();
            myClass.defaultMethod();
            MyInterface.staticMethod();
    
            Shape circle = new Circle();
            circle.draw();
            circle.calculateArea();
    
            Shape rectangle = new Rectangle();
            rectangle.draw();
            rectangle.calculateArea();
    
        }
    }
    
  • The difference between interface and abstract class

    • Abstract classes can have concrete implementations of methods, while methods in interfaces are abstract (except for default methods and static methods).
    • Abstract classes can have constructors, but interfaces cannot.
    • A class can only inherit one abstract class, but can implement multiple interfaces.
    • Interfaces are mainly used to define specifications, while abstract classes are mainly used for code reuse.

InstanceOf keyword of Java object-oriented programming

  • InstanceOf keyword

    • In Java,instanceofis an operator that tests whether an object is an instance of a class, or an instance of the object's superclass or interface.
    • instanceofDetermine whether the object is an instance of a class at runtime and returntrueorfalse.
    public class InstanceOfDemo {
        public static void main(String[] args) {
            Object obj1 = 1;
            Object obj2 = "Hello World";
            Object obj3 = new Cat();
    
            System.out.println(obj1 instanceof Integer);
            System.out.println(obj2 instanceof String);
            System.out.println(obj3 instanceof Animal);
            System.out.println(obj3 instanceof Cat);
        }
    }
    
  • Things to note

    • useinstanceofWhen , make sure that the object reference variable is notnull, otherwise it will throwNullPointerException.
    • in useinstanceofAfter type judgment, if type conversion is required, forced type conversion (such as(ClassName) obj).
    • Try to avoid overusing it in your codeinstanceof, as it may break object-oriented polymorphism