Java learning plan 06: OOP object oriented

Posted by Anarchatos on Tue, 02 Nov 2021 09:11:26 +0100

object-oriented programming

The core idea of Java is oop

  1. What is object oriented
  2. Methods review and deepen
  3. Object creation analysis
  4. Three characteristics of object oriented
  5. Abstract classes and interfaces
  6. Internal class and oop practice

Process oriented & object oriented

  • Process oriented thought

    • The steps are clear and simple. What to do in the first step and what to do in the second step
    • The area effect process is suitable for dealing with some simple problems
  • Object oriented thought

    • Physical clustering, thinking mode of classification, which classifications are needed to solve problems first, 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 program. However, specific to micro operation, it still needs process oriented thinking to deal with it.

What is object oriented

  • Object oriented programming (OOP)

  • The essence of object-oriented programming: organize code in the form of classes and organize (encapsulate) arrays in the form of objects.

  • abstract

  • Three characteristics:

    • encapsulation
    • inherit
    • polymorphic
  • From the perspective of cognition, there are classes after existing objects. Objects are concrete things. Class is abstract, which is the abstraction of object.

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

Review methods and deepening

Definition of method
  • Modifier
  • Return type
public class Demo01 {
    //main method
    public static void main(String[] args) {


     * Modifier return value type method name (...){
     *     //Method body
     *     return Return value;
     * }

    public String sayHello(){
        return "hello,world";
    public int max(int a,int b){
        return a > b ? a : b ;//Ternary operator 
  • break: jump out of switch and end the difference between loop statement and return
  • Method name: pay attention to the specification, see the meaning of the name
  • Parameter list: (parameter type, parameter name)
  • Exception throw

Method call

  • Static method
  • Non static method
public class Demo02 {
    public static void main(String[] args) {
        //Static method static class name point method name

        //Non static methods instantiate this class new
        //Object type object name = object value;
        Student student=new Student();

    // static is loaded with the class
    public static void a(){

    //Class exists after instantiation
    public void b(){

//Student class
public class Student {

    public static void say(){
        System.out.println("Students speak, static method");
    public void say1(){
        System.out.println("Students speak,Non static method");

  • Formal and argument
  • Value passing and reference passing
  • this keyword

Relationship between class and object

  • Class is an abstract data type. It describes and defines a class of things as a whole, but it can not represent a specific thing.
    • Animals, plants, mobile phones, computers, etc
  • Objects are concrete instances of abstract concepts
    • Zhang San is a concrete example of people, and the prosperous wealth of Zhang San's family is a concrete example of enough
    • It is a concrete instance rather than an abstract concept that can reflect the characteristics and functions.

Creating and initializing objects

  • Create an object using the new keyword

  • When using the keyword, in addition to allocating memory space, the created object will be initialized by default and the constructor in the class will be called.

  • Class constructors, also known as construction methods, must be called when creating objects. Constructors have the following two characteristics:

      1. Must be the same as the class name
      2. There must be no return type and void cannot be written

Constructor details


  1. Same as class name
  2. no return value


  1. The essence of new is to call the constructor
  2. Initializes the value of the object


  1. After defining a parameterized construct, if you want to use a parameterless construct, you must display a parameterized construct

Ait+Insert auto generate constructor

//Alt+inset build constructor

public class Person {
    //Even if a class writes nothing, it will have a method
    //Display definition constructor
    String name;

    public Person(){
        //Instantiation initial value
        //Constructor function: when using the new keyword, there must be a constructor"name of a fictitious monkey with supernatural powers";
    //Parameterized structure: once a parameterized structure is defined, the definition of nonparametric structure must be displayed, otherwise it has no effect
    public Person(String name){;
public class Application {
    public static void main(String[] args) {
        //An object is instantiated using new
        Person person = new Person();



  • The dew that should be exposed, the hide that should be hidden

    • Our programming requires "high cohesion and low coupling". High cohesion means that the internal data operation details of the class are completed by ourselves, and external interference is not allowed; low coupling: only a small number of methods need to be 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.

    Property private, get/set

Benefits of encapsulation:

  1. Improve program security and protect data
  2. Implementation details of hidden code
  3. Unified interface
  4. System maintainability increased


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

  • Extensions means the extension of the parent class of a subclass.

  • 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 the subclass (derived class) and the other is the parent class (base class). The subclass inherits the parent class and is represented by the keyword extends.

  • In a sense, there is a "is a" relationship between a child class and a parent class.

  • object class

  • Comparison between super and this

    • super Note:
          1.super The constructor of the parent class must be called in the first instance of the constructor
          2.super Must only appear in subclass methods or constructors!
          3.super and this Constructor cannot be called at the same time!
      Vs this: 
          The objects represented are different:
              this:The object itself is the caller
              super:Represents the application of the parent object
              this:Can be used without inheritance
              super:Can only be used in inheritance conditions
          Construction method
              this():Construction of this class
              super():Construction of parent class!
  • Method rewrite

  • //Static methods and non static methods are very different!
    public static void main(String[] args) {
       //Method is related to the data type defined on the left.
        A a = new A();
        //A reference to a parent class points to a child class
        B b = new A();//Non static method. The subclass overrides the method of the parent class.
Override: inheritance relationship is required. The subclass overrides the method of the parent class!
    1. Method names must be the same
    2.The parameter list must be the same
    3.Modifier: can expand but not shrink:    public>protected>Default
    4.Exception thrown: the scope can be reduced, but not expanded ClassNotFoundException -->Exception
    The methods of overriding subclasses and superclasses are the same, but the method bodies are different!
Why rewrite?
    1.The function of the parent class and the subclass are not necessarily required or satisfied!
    Ait + Insert : override;


  • That is, the same method can adopt many different behavior modes according to different sending objects.

  • The actual type of an object is determined, but there are many reference types that can point to the object (parent class, related class)

  • Conditions for the existence of polymorphism

    • There is an inheritance relationship
    • Subclass overrides parent method
    • The parent class application points to the child class object
  • Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes.

public class Application {
    public static void main(String[] args) {
         * The actual type of an object is determined
         * new Student();
         * new Person();
        //The methods that student s can call are their own or inherit the parent class
        Student s1 = new Student();
        //The Person parent type can point to subclasses, but cannot call subclass methods
        Person  s2 = new Student();;;
public class Student extends Person{    @Override//Override the method public void run() {system. Out. Println ("student run");}}
public class Person {    public void run(){        System.out.println("Person run");    }}/*Polymorphic considerations: 1. Polymorphic is a polymorphic method, but the attribute is not polymorphic. 2. Parent and child classes are associated with type conversion exception ClassCastException3. Existence conditions: inheritance relationship, method rewriting, parent class reference pointing to class cannot be rewritten: 1.static method belongs to class, but it does not belong to instance constant 3.private method */
  • instanceof type conversion ~ conversion of reference type
public class Application {    public static void main(String[] args) {         //Conversion between types: parent and child person student = new student(); System.out.println(student instanceof Object);        // Student converts this object to student type, and we can use the method of student type ((Student)student).go()// When a subclass turns to a parent class, it may lose some of its original methods}} / * 1. The reference of the parent class points to the object of the subclass. 2. When a subclass turns to the parent class, it may lose some of its original methods. 3. When the parent class turns to the rotor class, it will transform downward. 4. Facilitate the call of methods and reduce duplicate codes! Concise abstraction: encapsulating inheritance polymorphism*/

instanceof determines whether there is an association

abstract class

  • The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method; If you modify a class, it is an abstract class.

  • Abstract classes can have no abstract methods, but classes with abstract methods must declare abstract classes.

  • Abstract classes cannot use the new keyword to create objects. It is used to let subclasses inherit.

  • Abstract methods have only method declarations and no method implementations. They are used to implement subclasses.

  • If a subclass inherits an abstract class, it must implement an abstract method that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class.

//Abstract class / / class extensions: it is a single inheritance interface (multiple inheritance) public abstract class Action {/ / constraint ~ I hope someone can help me implement / / abstract. Abstract methods only have method names, but no method implementations. public abstract void doSomething() ; / / an abstract class cannot be new, but can only be implemented by subclasses. / / ordinary methods can be written in an abstract class. / / abstract methods must be in an abstract class.}


  • Common class: only concrete implementation
  • Abstract classes: concrete implementations and specifications (abstract methods)
  • Interface: only specifications
  • An interface is a specification, and a definition is a set of rules.
  • The essence of an interface is a contract. Just like us, we all abide by it after it is formulated
  • The essence of OO is the abstraction of objects. The interface is the best embodiment of this. Why do we discuss design patterns only for languages with abstract ability (not as good as c++ java c# and so on), which is what a design pattern studies. In fact, it is how to abstract reasonably
public interface UserService {    //All definitions of interfaces in are abstract public abstract void add (string name); void delete(String name);     void update(String name);     void query(String name);}
//Class can implement the interface implements / / it implements the class in the interface. You must override the methods in the interface public class userserviceimpl implements userservice, timeservice {@ override public void add (string name) {} @ override public void delete (string name) {} @ override public void update (string name) {}     @Override    public void query(String name) {    }    @Override    public void timer() {    }}
Function of interface:    1.constraint    2.Define some methods for different people to implement    3.The methods are public abstract    4.public static final    five.The interface cannot be instantiated. The interface has no constructor    5.Interfaces can be used for multiple purposes implements realization    six.Implementing interfaces must override methods

Topics: Java Back-end