JAVA Object Oriented Programming Notes

Object oriented programming (OOP)

Process oriented & object oriented

  1. Process oriented thought
    • The steps are clear and simple. What is the first step and what is the second step
    • Process oriented is suitable for dealing with some simple problems
  2. Object oriented thought
    • Birds of a feather flock together, classify thought patterns, think about problems, first solve problems, 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.
  3. 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 system. However, specific to micro operation, it still needs process oriented thinking to deal with it.

object-oriented

  • Object oriented programming (OOP)
  • The essence of object-oriented programming: Organize code in the form of classes and organize (encapsulate) data in the form of objects.
  • abstract
  • Three characteristics
    • Packaging: divide and package the data.
    • Inheritance: descendant parent
    • Polymorphism:
  • From the perspective of epistemology, there are objects first and then classes.
    • Object: is a concrete thing
    • Class: it 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.

Relationship between class and object

  1. Class is an abstract data type. It is an overall description / definition of a class of things, but it can not represent a specific thing.
    • Animals, plants, mobile phones, computers
    • Person class, Pet class, Car class, etc. these classes are used to describe / define the characteristics and behavior of a specific thing
  2. Objects are concrete instances of abstract concepts
    • Zhang San is a concrete example of man,

Creating and initializing objects

  • 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 and the constructor in the class will be called.

  • practice:

    • First, create a student class Student.java
    package com.LTF.oop.test2;
    
    public class Student {
    
        //Attribute field name
        String name;
        int age;
        String sex;
    
    
        //method
        public void study(){
            System.out.println("full name:"+this.name+",Age:"+this.age+",He is studying hard......");
        }
    
    }
    
    
    • Then create a class of the main method

      package com.LTF.oop.test2;
      
      //Only one main method should exist for a project
      public class Application {
          public static void main(String[] args) {
      
              //Class: abstract, instantiated
              //Class will return its own object after instantiation
              //A student object is a concrete instance of a student class
              Student xiaoming = new Student();
              Student xiaohong = new Student();
      
              xiaoming.name = "Xiao Ming";
              xiaoming.age = 13;
              xiaoming.sex ="male";
              xiaohong.name ="Xiao Hong";
              xiaohong.age = 13;
              xiaohong.sex ="female";
      
              System.out.println(xiaoming.name+"this year"+xiaoming.age+"Years old. What's his gender"+xiaoming.sex);
      
              xiaohong.study();
          }
      }
      
      

Construction method

If a class does not write anything, there will also be a construction method (i.e. implicit construction) by default, which can be used directly

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

    • The method name must be the same as the class name
    • There must be no return type and void cannot be written
  • The construction method must be mastered

  • Parameterless constructs can be used to instantiate initial values

  • Note: parameterized Construction: once a parameterized construction is defined, the nonparametric construction (i.e. explicit construction) must be written out (method overloading)

  • The role of the constructor core:

    1. When using the new keyword, there must be a constructor. Instantiation is essentially calling the constructor
    2. Initializes the value of the object

Shortcut keys: alt+insert - > constructor - > select parameters and click OK to automatically generate a parameterized constructor (or click select None to automatically generate a parameterless constructor)

package com.LTF.oop.test2;

public class Student {

    //Attribute field name
    String name;
    int age;
    String sex;
    
    //Explicit nonparametric construction
    public Student() {
    }
    //Parametric structure
    public Student(String name) {
        this.name = name;
    }
}

New object memory analysis

Put some references to methods and variables on the stack, stack objects, and the method area is in the heap

encapsulation

  • The dew should be hidden

    • Our programming should pursue: "high cohesion, low coupling". High cohesion means that 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 an object's data 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

  • practice

    Application.java

    package com.LTF.oop.test3;
    
    public class Application {
        public static void main(String[] args) {
            Student s1 = new Student();
    
            s1.setName("Xiao Ming");
            //Judging whether two methods in a class are the same (method overloading) requires two aspects: method name and parameter list
            System.out.println(s1.getName());
    
            s1.setAge(-1);//wrongful
            System.out.println(s1.getAge());
    
        }
    }
    
    

    Student.java

    package com.LTF.oop.test3;
    //Class private: private
    public class Student {
    
        //Property private
        private String name;  //full name
        private int id;   //Student number
        private char sex;   //Gender
        private int age;  //Age
    
        //Provide some methods that can manipulate this property
        //Some public get set methods are provided
    
        //get gets this data
        public String getName(){
            return this.name;
        }
    
        //set sets a value for this property
        public void setName(String name) {
            this.name = name;
        }
    
        //The alt+insert shortcut can be used to automatically generate the get set method
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public char getSex() {
            return sex;
        }
    
        public void setSex(char sex) {
            this.sex = sex;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            if(age<120||age>0) {
                this.age = age;
            }else{
                this.age=3;//wrongful
            }
        }
    }
    
    

inherit

  • The essence of inheritance is to model a group of class objects, so as to better model 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 relationship between classes. In addition, the relationships between classes include 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).

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

  • object class

    //In Java, all classes inherit the Object class directly or indirectly by default. Subclasses can use all methods of Object
    
    //Shortcut key: ctrl + H to open the inheritance tree and view the inheritance relationship
    

    The Object class is located in the java.lang package and will be automatically imported during compilation. When we create a class, if we do not explicitly inherit a parent class, it will automatically inherit Object and become a subclass of Object.

  • super

    	this.name;   //Call the name attribute in the current class
        super.name;  //Call the name attribute in the parent class
    	this.test();  //Call the test() method in the current class
        super.test();  //Call the test() method in the parent class
    //If the modifier of a property or method in the parent class cannot be private, it cannot be called.
    
    • In the parameterless construction, there is a hidden sentence in the parameterless construction of subclasses:

    • Super();
      
    • It calls the parameterless construction of the parent class, so when creating a new subclass object in the main function, the parameterless construction of the parent class is executed first, and then the parameterless construction of the subclass is executed.

      Moreover, if this sentence is explicit, the sentence calling the parent class must be the first sentence to be constructed without parameters in the child class, otherwise an error will be reported.

    • Note:

      1. super calls the constructor of the parent class, which must be in the first sentence of the constructor.
      2. super must only appear in subclass methods or constructor methods!
      3. super and this cannot call constructors at the same time, because they must both be in the first sentence. You can't have both.
    • Vs this

      1. Different representative objects: this: the caller of the object itself, and super: the application of the parent object
      2. Premise: this: it can be used without inheritance; super: it can only be used under the condition of inheritance.
      3. Construction method: this(); Construction of this class, super(); Construction of the parent class.
  • Method override

    Rewriting is the rewriting of methods, which has nothing to do with attributes. It is only related to non static methods, and there must be inheritance relationship. The subclass rewrites the methods of the parent class.

    1. Method names must be the same
    2. The parameter list must be the same
    3. Modifier: the scope can only be expanded but not reduced. Public > protected > Default > private
    4. Exception thrown: the scope can be narrowed, not expanded.

    Override: the methods of the child class and the parent class must be consistent, and the method bodies are different!

    Why rewrite?

    1. The functions of the parent class and the child class are not necessarily required or satisfied.
    2. Shortcut key: ALT + insert: select override.

    The reference of the parent class points to the child class: for example, B is the parent class of A, B b = new A();

    There are static methods and non static methods

    Big difference

    Static methods are methods of classes, while non static methods are methods of objects.

    The call of static method is only related to the left, that is, the defined data type B, and has nothing to do with new. B calls the method of class B, because B is defined by class B

    The call of non static methods is related to objects, that is, new, b is the object from class A new, and b calls class A methods, that is, polymorphic. As long as the subclass overrides the method of the parent class, the subclass's method will be executed.

Methods that cannot be overridden:

  • static method belongs to class, not instance,
  • final constant
  • The private method is private and cannot be overridden

polymorphic

The same method can adopt many different behavior modes according to different sending objects.

The actual type of an object is certain, that is, what you new is, but there are many types of references that can point to the object

The methods that an object can execute mainly depend on the type on the left of the object, which has little to do with the right!

Conditions for polymorphism:

  • There is an inheritance relationship
  • The subclass overrides the parent method
  • The parent class reference points to the child class object B b = new A();

Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes.

Parent and child classes are related and cannot be forcibly converted to other irrelevant types. Type conversion exceptions and ClassCastException are reported

  • The methods that can be called by subclasses are only their own or parent class methods
  • A parent class can point to a subclass, but cannot call methods unique to a subclass. Only when a subclass or subclass overrides its own method, the method overridden by the subclass is executed.

instanceof and type conversion

instanceof (type conversion) refers to the type and determines what type an object is~

It can be used to judge whether there is a parent-child relationship between two classes, and then to see whether the type pointed to by X is a subtype of Y. Provided that x = new y(); Or x = subtype of new y ();.

System.out.println(x instanceof y); //Whether the compilation can pass or not, there is a parent-child relationship if the compilation passes, and there is no parent-child relationship if it fails.

Note:

  • The parent class refers to an object that points to a child class
  • Convert a subclass to a parent class and transform upward without forced conversion
  • Converting a parent class to a child class, downward transformation and forced transformation may lose some methods, which is not very good.
  • Facilitate method calls and reduce duplicate code

Static keyword explanation

  1. Non static variables cannot be accessed by class name, but can be accessed by instantiating an object.

  2. It is recommended that it is more convenient to use class name to call static variables. Static static: when the class is loading, static properties or static methods exist, that is, they are loaded into memory, so they can be used directly. Non static ones can only be used after the class is loaded and instantiated.

    package com.LTF.oop.test5;
    
    public class Student {
    
        private static int age; //Static variable
        private double score;  //Non static variable
    
        public void run(){      //Non static method
          go();
        }
        public static void go(){   //Static method
    
        }
        public static void main(String[] args) {
            //instantiation 
            Student s1 = new Student();
    
            System.out.println(Student.age);//Class name. Static variable
            //System.out.println(Student.score);
            // Error, non static variables cannot be called with a class name.
            System.out.println(s1.score);
            System.out.println(s1.age);
    
            new Student().run();    //Calling non static methods through new instantiation
            go();  //Use static methods directly.
            Student.go();   //Class name. Static method name, calling
    
        }
    }
    
    
  3. Static code block

    package com.LTF.oop.test5;
    
    import java.sql.SQLOutput;
    
    public class Person {
    
        //Loading order: 1. Static code block 2. Anonymous code block 3. Construction method
        //2. It can be used to assign initial value. It appears at the same time as the object.
        {
            //Code block (anonymous code block)
            System.out.println("Anonymous code block");
        }
        //1.Static is executed only once
        static{
            //Code block (static code block)
            System.out.println("Static code block");
        }
    
        //3.
        public Person(){
            //Construction method
            System.out.println("Construction method");
        }
    
        public static void main(String[] args) {
            Person p1 = new Person();
            System.out.println("#######################");
            Person p2 = new Person();
        }
    }
    
    
  4. You can statically import the methods in the Math class. When the methods in the Math class are used in the Test class, you don't need to use the class name. The method name is as follows:

    package com.LTF.oop.test5;
    
    import static java.lang.Math.random;  //Static import random method
    
    public class Test {
        public static void main(String[] args) {
    
            System.out.println(random());
            //You can use the random method directly
        }
    }
    
    
  5. final

    A class modified by final cannot be inherited.

abstract class

The significance of abstract class is to abstract the public class without repeated declaration and definition, so as to improve the development efficiency.

  1. The abstract modifier can be used to modify methods or classes. If you modify a method, the method is an abstract method; If you modify a class, it is an abstract class.
  2. Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes. That is, abstract methods must be in abstract classes.
  3. An abstract class cannot use the new keyword to create an object. It is used to allow subclasses to inherit
  4. Abstract methods have only method declarations and no method implementations. They are used to implement subclasses.
  5. 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.
  6. This abstract class cannot be new. It can only be implemented through subclasses: constraints and abstract classes cannot be instantiated.
  7. Abstract classes are rules and constraints. Without rules, there is no place. Abstract abstract

Definition and implementation of interface

  1. Common class: only concrete implementation
  2. Abstract classes: concrete implementations and specifications (abstract methods) are available
  3. Interface: only specification! I can't write my own methods ~, and I specialize in constraint, separation of constraint and Implementation: interface oriented programming.
  • An interface is a specification. It defines a set of rules, which embodies the idea of "if you are..., you must be able to...".
  • The essence of an interface is a contract, just like the law between us. After it is formulated, everyone will abide by it.
  • The essence of interface is the abstraction of objects

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

Interfaces can inherit multiple.

effect:

  • constraint
  • Define some methods for different people to implement.
  • All defined methods in the interface are actually abstract, public abstract
  • The attributes defined in the interface are static constants, public static final
  • The interface cannot be instantiated ~, and there is no constructor in the interface because it is not a class. Where does the constructor come from.
  • Multiple interfaces can be implemented through the keyword implements.
  • When implementing an interface, you must override the methods in the interface

practice

Interface UserService.java

package com.LTF.oop.test7;
//Keywords defined by interface
public interface UserService {
    //The attributes defined in the interface are static constants, public static final
    //Constants are generally not defined in the interface.
    int age =99;

    //All defined methods in the interface are actually abstract, public abstract
    //Four interface methods are defined and cannot be implemented here. There must be an implementation class
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);
}

Interface TimeService.java

package com.LTF.oop.test7;

public interface TimeService {
    void timer();
}

Implementation class UserServiceImpl.java

package com.LTF.oop.test7;
//Abstract class: Extensions inheritance only has single inheritance, but interfaces have multiple inheritance
//implements: implementation keyword
//The class that implements the interface must override the method in the interface
public class UserServiceImpl implements UserService,TimeService{
    //Example: the interface inherits both UserService and TimeService
    //Shortcut key CTRL+i to realize the interface method
    @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() {

    }
}

N internal classes

An internal class is to redefine a class within a class. For example, if a class B is defined in class A, class B is called an internal class relative to class A, and class A is an external class relative to class B.

  • Member inner class

  • Static inner class

    A Java class can have multiple class classes, but only one public class

  • Local inner class

  • Anonymous Inner Class

Keywords: Java

Added by VertLime on Wed, 06 Oct 2021 18:17:03 +0300