Java object oriented

Java object oriented

Static / non static method

Static methods can only call static methods. Non static methods can call static methods:

    public static void main(String[] args) {
        //Static method static can be called directly with class name and method name
        //Non static methods need to instantiate this class new first
        Student student = new Student();
        student.say();
    }

    public static void a(){
        //b();   An error will be reported when calling B, because static is loaded with the class, and B () is not loaded at this time
    }
    //Class does not exist until it is instantiated
    public void b(){
    }

Value passing and reference passing

Ordinary function: the parameter passed in is a copy

//Reference passing: object, essence or value passing
public class demo03 {
    public static void main(String[] args) {
        Person person =new Person();
        System.out.println(person.name);    //null
        demo03.change(person);
        System.out.println(person.name);    //xxx
    }

    public static void change(Person person){
        person.name = "xxx";    //Because person is an object pointing to -- > person person - New person(), which is a specific person who can change the attribute
    }
}

class Person{
    String name;
}

constructor

  • A class will have a method (constructor) even if it despises everything

  • The constructor in a class, also known as a constructor, must be called when creating an object. And the constructor has 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

public class Person {
    String name;

    //Function: initial value
    //1. Using the new keyword is essentially calling the constructor
    //2. Used to initialize values
    public Person(){
        //constructor 
        this.name = "alingo";
    }

    //Parameterized Construction: once a parameterized construction is defined, no parameters must be explicitly defined
    public Person(String name){
        this.name = name;
    }

    //alt + insert automatically generates constructors (constructed according to attributes)

}

Create object memory analysis

public class Pet {
    public String name;
    public int age;

    public void shout(){
        System.out.println("Let out a cry");
    }
}
//There should be only one main method in a project
public class Application {
    public static void main(String[] args) {
        Pet dog = new Pet();
        dog.name = "Wangcai";
        dog.age = 3;
        dog.shout();

        Pet cat = new Pet();
    }
}

encapsulation

High cohesion, low 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

Property private, get/set

  • private keyword

inherit

  • Key words: Extensions subclass (derived class) is an extension of the parent class

  • Java classes only have single inheritance, not multiple inheritance! (a son can only have one father, but a father can have multiple sons)

  • There are also combinatorial relationships:

    public class Student {
        Person person;
    }
    
  • If a subclass inherits from the parent class, it will have all the public methods and properties of the parent class

//In Java classes, all classes inherit the Object class directly or indirectly by default
public class Person /*extends Object*/{
    // The default is public
    //private
    //protected

    private int money = 10_0000_0000;


    public void say(){
        System.out.println("Said a word");
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}
  • Ctrl + H to display the tree class directory

super note:

  • super calls the constructor of the parent class, which must be in the first instance of the constructor

  • super must only appear in subclass methods or constructor methods

  • super and this cannot call constructor at the same time

Vs this:

  • This is the object of the caller

  • super: represents the application of the parent object

Premise:

  • this: can be used without inheritance

  • siper: can only be used in inheritance conditions

Construction method:

  • this();      Of this class

rewrite

  • Inheritance relationship is required. The subclass overrides the method of the parent class

  • Method names must be the same

  • The parameter list must be the same (otherwise it will be overloaded)

  • Modifier: the scope can be expanded: public > protected > Default > private

  • Exception thrown: the scope can be narrowed, but cannot be expanded:

    Classnotfoundexception -- > exception (large)

Why rewrite:

  • The functions of the parent class and the child class are not necessarily required or satisfied

Alt + Insert: override

Static method:

public static B{
    public static void test(){
        System.out.println("B");
    }
}

public static A extends B{
    public static void test(){
        System.out.println("A");
    }
}

A a = new A();
a.test();//Output A

//A reference to a parent class points to a child class
//Method is only related to the data type defined on the left
B b = new A();
b.test();//   Output B

Non static methods: overriding

public class B {
    public void test(){
        System.out.println("B");
    }
}

public class A extends B{
    //Override override
    @Override   //Comments: functional comments!
    public void test() {
        System.out.println("A");
    }
}

        A a = new A();       //The output is A

        a.test();
        B b = new A();       //The output is still A, because the subclass overrides the methods of the parent class, which is only valid in non static methods, because the non static methods are loaded at creation time

        b.test();

Static methods are very different from non static methods

Static method: the call of the method is related to the left, that is, the defined data type

Non static: overriding

polymorphic

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

  • The actual type of an object is determined, but the reference type is uncertain

        Student s1 = new Student();
        //The methods that students can call are their own or inherit the parent class

        //The Person parent type can point to subclasses, but cannot call methods unique to subclasses
        //The type of reference that can be pointed to is uncertain
        Person s2 = new Student();  //Person is the parent class of Student. Here, the reference of the parent class points to the child class
        Object s3 = new Student();  //Similarly

//It is also a Student object, but it has different states: polymorphism
        
        s1.eat();
        s2.eat();

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

Therefore, the reference pointed to by the child class is different from that pointed to by the parent class

  • The methods that can be called by a subclass are their own or inherit from the parent class

  • A parent type can point to a subclass, but cannot call methods unique to a subclass

Precautions:

  • Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes

  • For parent and child classes, type conversion can only be performed if they are associated with parent and child classes. Otherwise, type conversion exception occurs: ClassCastException

  • Existence condition: the inheritance relation method needs to be overridden. The parent class reference points to the child class object. Father f1 = new Son();

  • Methods that cannot be overridden:

    • static method, which belongs to class, does not belong to instance

    • final constant

    • private

instanceof and type conversion

instance of determines whether there is a parent-child relationship between two classes

When compiling, the judgment is on the left, that is, if the data type does not meet the parent-child relationship, it will directly report an error

And running it as false is to judge the object on the right

        Object object = new Student();
        System.out.println(object instanceof Student);  //true
        System.out.println(object instanceof Person);   //true
        System.out.println(object instanceof Object);   //true
        System.out.println(object instanceof  String);  //false

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

Type conversion

//High and low
Person student = new Student();   //From low to high, you do not need to cast a subclass to a parent class, and you may lose some of your original methods

Student student = (Student) obj;    //High to low requires cast 

summary

  • A parent class reference points to a child class object (not vice versa)

  • The subclass is transformed into the parent class and transformed upward without forced type conversion

  • To convert a parent class into a child class and transform downward, you need to force conversion

static

Static variables are shared by all objects (instances) of a class. When the class is directly used to call, it also shows that this variable is static:

public class Student {
    private static int age; //Static variable
    private double score;   //Non static variable

    public static void go(){

    }

    public void run(){
        go();       //Non static functions can call static functions, but not vice versa, because static functions are loaded first
    }
    public static void main(String[] args) {
        Student s1 = new Student();
        System.out.println(Student.age);
        //System.out.println(Student.score);     An error will be reported because score is not a static variable
        System.out.println(s1.age);
        System.out.println(s1.score);

        Student.go();
        go();
        //Student.run();     An error will be reported. The non static method must be used after the object is new
    }
}
public class Person {
    //Sequence 2: generally used to assign initial values
    {
        System.out.println("Anonymous code block");
        //The code block (anonymous code block) is created when the object is created and before the constructor function
    }
    //Execute only once sequence: 1
    static{
        System.out.println("Static code block");
        //Static code blocks and classes are executed when they are loaded, and only once
    }
    //Sequence: 3
    public Person() {
        System.out.println("Construction method");
    }

    public static void main(String[] args) {
        Person person = new Person();       //Static code block, anonymous method block and construction method are output respectively

        Person person2 = new Person();        //Only anonymous code blocks and construction methods are output
    }
}

Static import

import static java.lang.Math.random;
import static java.lang.Math.PI;
public class Test {
    public static void main(String[] args) {
        System.out.println(Math.random());  //You need to add Math before importing

        //After static import, you can call it directly
        System.out.println(random());
        System.out.println(PI);
    }
}

Keyword final:

Is a keyword that modifies a constant. After modification, it can no longer have subclasses and can no longer be inherited

abstract class

Modify with abstract keyword

//Abstract abstract class: class extensions: single inheritance has limitations (interfaces can inherit more than one)
public abstract class Action {
    //Constraints let others help us achieve
    //Abstract abstract abstract methods only have method names and no method implementations
    public abstract void doSomething();

    //1. You can't use the abstract class new. You can only rely on subclasses to implement it: constraints!
    //2. Ordinary methods can be written in abstract classes
    //3. Abstract methods must be in abstract classes

    //Significance of existence: abstract it to improve development efficiency
}

Interface

  • Common class: only concrete implementation

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

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

An interface is a specification. The essence of an interface is a contract and an abstraction of an object

Define with interface keyword

effect:

  • constraint

  • Define some methods for different people to implement

  • Method: public abstract

  • Attribute: public static final

  • The interface cannot be instantiated. There is no constructor in the interface

  • implements can implement multiple interfaces

  • The method of the interface must be overridden~

public interface TimeService {
    void timer();
}


//All keyword interfaces defined by interface need to have implementation classes
public interface UserService {
    //The default type of the property is public static final int AGE = 99 constant
    int AGE = 99;
    //In fact, all definitions in the interface are public abstract s
    void add(String name);
    void delete(String name);
    void update(String name);
    void query(String name);
}

Inner class

  • Member inner class
    public class Outer {
    private int id=10;
    public void out(){
        System.out.println("This is the method of an external class");
    }
    public class Inner{
        public void in(){
            System.out.println("This is the method of the inner class");
        }
        //Get the private properties of the external class~
        public void getID(){
            System.out.println(id);
        }
    }
}

    public static void main(String[] args) {
        Outer outer = new Outer();
        //Instantiate the inner class through this outer class
        Outer.Inner inner = outer.new Inner();
        inner.getID();       //10

    }
  • Static inner class
public class Outer {
 private int id=10;
 public void out(){
 System.out.println("This is the method of an external class");
 }
 public static class Inner{
 public void in(){
 System.out.println("This is the method of the inner class");
 }
 //At this time, an error will be reported and private cannot be obtained, because public will be executed first unless the attribute is also static
 public void getID(){
 System.out.println(id);
 }
 }
 }
  • Local inner class
public class Outer {

    //Local inner classes are classes written in methods
    public void method(){
        class Inner{
            public void in(){

            }
        }
    }
}
  • Anonymous Inner Class

Added by joshuaceo on Sat, 30 Oct 2021 18:11:21 +0300