Java object oriented

Posted by vitorjamil on Fri, 22 Oct 2021 14:49:08 +0200

1. Object oriented overview

Process oriented: specific, step-by-step, suitable for dealing with simple problems.

**Object oriented: * * is abstract. To solve problems, first classify them and think about the divided classes separately. It is suitable for dealing with complex problems and multi person cooperation problems. However, the detailed problems after classification still need to be solved process oriented.

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

OOP has three characteristics: encapsulation, inheritance and polymorphism

From the perspective of Epistemology: there are objects before classes! Objects are concrete, classes are abstract, and classes are abstractions of objects.

From the perspective of code operation: first class, then object! A class is a template for an object

2. Review and deepen methods

  1. Static and non static methods
  • In different classes

    The static method can be called directly, but the non static method must be instantiated and called.

  • In a class

​ 📜 Non static methods can be called directly to each other

​ 📜 Static methods can also call each other directly

📜 However * * static methods cannot call non static methods*

⭐ Because static methods and classes are loaded together, and non static methods only exist after class instantiation (New), errors will occur if existing calls do not exist

  1. pass by value
public class pass by value {
    public static void main(String[] args) {
        int a=1;
        change(a);
        System.out.println(a);//Output 1

    }
    //The return value is null
    public static void change(int a) {
        a =100;//What changes is parameter a
    }
}
  1. Reference passing
//Reference passing: is it an object, essence or value

//There can only be one public class, but there can be multiple classes
class Person{
    String name;//One attribute: name
}

public class Reference passing {
    public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.name);   //Output null

        Reference passing.change(person);
        System.out.println(person.name);   //Output ssss
    }

    public static void change(Person per) {
        //per is an object that points to the person passed
        per.name="sssss";
    }
}

3. Object creation and analysis

  1. Relationship between class and object

​ ❗ Class is an abstract data type. It is the overall description / definition of a certain kind of things. It is a template and cannot represent a specific thing!!!

​ ❗ Objects are concrete instances of abstract concepts, and objects (in the heap) are operated by reference (in the stack)

  1. Creation of classes and objects
  • Create class
public class Pet {

    //Attribute: also known as Field or member variable
    //Attribute composition modifier + attribute type + attribute name = attribute value;
    //Default attribute number: 0.0, char:u0000, boolean:false, reference: null
    public int age;
    public String name;

    //Using the default parameterless constructor

    //method
    public void shout() {
        System.out.println(this.name+"Let out a cry");
    }

}
  • create object

Use the new keyword to create an object. When creating a new object, in addition to allocating memory space, it also performs default initialization (for example, property initialization) for the created object and calls to the constructor in the class.
3. Constructor

Even if a class does not write anything, there will be a default constructor


Constructors in classes, also known as construction methods, must be called when creating objects. The main functions are: when new creates an object, it essentially calls the constructor and initializes the value; And the constructor has the following two characteristics:

  • Must be the same as the class name
  • No return type, can't write void!!

If a constructor is defined artificially (a constructor is displayed and defined), some information can be initialized, which can be divided into nonparametric constructor and parametric constructor

  • Parameterless constructor

  • Parametric constructor

    ❗ Once a parameterized constructor is defined, the definition of a parameterless constructor must be displayed. The parameterless constructor can write nothing

    Shortcut key for creating constructor: alt+insert

  1. Create a memory analysis of the object

    When creating an object, the object name, that is, the reference variable name, is in the stack, and the actual new object is in the heap

4. Three characteristics of object-oriented

1. Packaging

Encapsulation is mainly for attributes in a class

Property private; get / set: provides some methods that can manipulate properties

Shortcut key: alt+insert generate get/set method

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

The program design requires "high cohesion and low coupling". High cohesion: the internal data operation details of the class are completed by themselves without external interference; low coupling: only a small number of methods are exposed for external use.

Encapsulation is mainly for attributes in a class

  • Meaning of encapsulation
  1. Improve program security and judge the security of incoming data
  2. Hide details of data operations
  3. The maintainability of the system is improved
  4. Unified interface, all of which are get/set methods
public class Student {
    //Property private
    private String name;
    private int id;
    private char sex;

    //Provides methods to manipulate properties
    //Provide public get/set methods
    //get gets the value of the data
    public String getName() {
        return this.name;
    }
    //set sets the value of the data
    public void  setName(String name1) {
        this.name=name1;
    }

    public int getId() {
        return id;
    }
    public void setId(int id1) {
        if (id1>0 && id1<100) {
            //Data security inspection
            this.id = id1;
        }else {
            System.out.println("Illegal student number");
        }
    }

    public char getSex() {
        return sex;
    }
    public void setSex(char sex) {
        this.sex = sex;
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.setName("San Ji");
        System.out.println(s1.getName());

        s1.setId(105);//Illegal student number output

    }
}

2. Inherit extensions

The relationship between classes: inheritance, dependency, composition, aggregation, etc.

The essence of inheritance is to abstract a group of classes to better model the real world. extend means "extension", that is, a subclass is an extension of a parent class. A subclass is also called a derived class; a parent class is also called a base class.
Private properties or methods in the parent class cannot be inherited. All classes in Java inherit the Object class directly or indirectly by default

❗ In Java, there is only single inheritance, not multiple inheritance, and only one class can be directly inherited (a son can only have one father)

Shortcut key: CTRL+H to open inheritance tree

⭐️ super

  • super can only be used under inheritance conditions

  • In subclasses, you can call public / protected properties or methods in the parent class through super +

  • When you create a subclass, you always call the parameterless constructor of the parent class first. If you use super() to explicitly call the parameterless constructor of the parent class, you need to put super() in front of the parameterless constructor of the subclass

  • super and this cannot call constructor at the same time!
    ⭐ ⒋ method override

[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-wpxwxrfk-1632832501782) (object-oriented. assets/image-20210928164709569.png)]

Method rewriting has nothing to do with static methods, only with non static methods

The premise of method rewriting is to have an inheritance relationship. It is a non static method in which a subclass rewrites the parent class

Shortcut key: alt+insert

Method rewrite
The premise of rewriting is: there is an inheritance relationship, and the subclass overrides the method of the parent class
The method name is the same, but the method body is different
The parameter list must be the same
Modifier: the scope can only be expanded, that is, the access permission of the subclass is greater than or equal to the access permission of the parent class public > protected > Default > private
Return type: the return type of the subclass method is less than or equal to the return type of the parent method
Exception thrown: the exception range can only be narrowed, that is, the exception thrown by the child class is less than or equal to the exception thrown by the parent class
Meaning of rewriting
The function of the parent class. The child class does not necessarily need or meet the needs of the child class

3. Polymorphism

Polymorphism means that the same method can call different methods according to different references to objects.

Conditions for polymorphism: inheritance relationship, subclass overriding method of parent class. Parent class reference points to subclass object

Implement dynamic compilation (the final state of the type can only be determined during execution), so as to enhance scalability.

The methods that can be executed by an object in polymorphism (when there is an inheritance relationship) mainly depend on the left side of the object. If there is this method on the left, it can be called, and if there is no error, it will be reported. If both parent and child classes have the method, but the child class overrides the method of the parent class, the method overridden by the child class is called.

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

polymorphic
Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
Polymorphism exists in parent-child classes with inheritance relationship, otherwise type conversion exception ClassCastException will occur
Method rewrite
The parent class reference points to the child class object Father f=new Son();

Note what methods cannot be rewritten! For example, a method modified by static (belonging to a class but not an instance), a method modified by final, and a method modified by private

  • instanceof

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

X instanceof Y to see whether the object pointed to by the X reference is a subtype of Y. if yes, it will return true; if no, it will return false. If there is no inheritance relationship between class X and Class Y, an error will be reported during compilation

  • Type conversion

Conversion between basic types, high to low - strong, low to high - Automatic

The above rules are also followed between reference types

5. Abstract classes and interfaces

1. Abstract class

Adding the keyword abstract in front of a class becomes an abstract class, abstracting common attributes and improving development efficiency

Abstract classes cannot inherit more than one

Abstract methods have no method body. In a class, only the method name is declared without implementing the method body. Adding the keyword abstract before the method becomes an abstract method. Abstract methods cannot exist separately from abstract classes.

Ordinary methods can also appear in abstract classes

//abstract class
public abstract class Action {

    //Abstract methods, someone helped us implement them
    //Abstract methods must be in abstract classes
    public abstract void run();
    
    //Common method
    public void eat() {
        System.out.println("time to have a meal");
    }
    
}

**If there are abstract methods in the abstract class * *, the subclass inheriting the abstract class must override these abstract methods unless the subclass is also an abstract class.

//All methods of an abstract class must be implemented by subclasses of the abstract class
//Unless the subclass is also an abstract class
public class A extends Action{
    @Override
    public void run() {
    
    }
}

An abstract class cannot be instantiated directly from new, but can only be implemented by its subclass NEW!, Although abstract classes have construction methods, the reason why they cannot be instantiated directly is that abstract classes are used for initialization rather than instantiation

Note: private is prohibited in the method permission modifier of abstract class, because the purpose of abstract class is to realize code reuse and facilitate subclass inheritance.

Abstract methods in abstract classes can only be decorated with public and default (protected before JDK 1.8, but default after JDK 1.8). Therefore, the access permission modifiers of subclasses of abstract classes can be public or protected

Only single inheritance can be realized in Java, but multiple inheritance can be realized by using interfaces

2. Interface

  • There are only concrete implementations in ordinary classes
  • There are both concrete implementations (i.e. ordinary methods) and specifications (i.e. abstract methods) in abstract classes
  • There are only specifications in the interface, and only constraints can be carried out, separating constraints from implementation

An interface is a specification. It defines a set of rules and is essentially a contract. It needs to be observed and implemented by different people. Interface is the essence of object-oriented and the abstraction of objects.

All methods defined in the interface are public abstract by default, which means that the interface needs to have implementation classes. Abstract methods have no method body.

Interface has no constructor

In JDK8, the methods in the interface can be modified by default and static, but!!! The modified method must have a method body.

All attributes defined in the interface are static constants public static final by default, but generally, attributes are not defined in the interface.

Interfaces, like abstract classes, cannot be instantiated directly because there is no constructor in the interface.

A class can implement multiple interfaces. The keyword implementation is required. The class must override the methods in the interface. Interfaces are different from classes. There are only method definitions in interfaces and method implementations in classes

Note: in the subclass of the interface, the access permission modifier of the subclass method cannot be lower than that of the parent class (the default permission of the parent class method is public abstract), so the subclass method can only be public

//Interface class
public interface UserService {

    //All attributes defined in the interface are static constants public static final by default
    public static final int age=18;

    //User service: add, delete, modify and query
    //All methods defined in the interface are abstract public abstract
    void add(String name);

    void delete(String name);

    void update(String name);

    void query(String name);
}
//Interface class
public interface TimeService {
    void timer();
}

//Class can implement the interface by using the keyword implementation
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() {

    }
}

6. Internal classes and OOP practice

1. Internal class

Inner class is to define a class inside a class. If a class B is defined in class A, class B is called an internal class relative to class A, and class A is called an external class relative to class B.

  1. Member inner class

❣️ Instantiation of an inner class requires calling an outer class

❣️ Internal classes can access private variables and private methods of external classes

public class Outer {
    private int id;
    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");
        }

        //Internal classes can access private variables and private methods of external classes
        public void getId() {
            System.out.println(id);
        }

        public void getMethod() {
            out();
        }
    }
}
  1. Static inner class

❣️ Internal classes cannot access private variables and private methods of external classes because static internal classes are instantiated first

  1. Local inner class

The variables defined in the method are local variables, and the classes defined in the method are local internal classes

public class Outer2 {
    public void method() {
        //The variables defined in the method are local variables
        int a=10;

        //Local inner class
        class  Inner {
            public void in() {
                System.out.println("This is the method of a local inner class");
            }
        }
        
    }
}
  1. Anonymous Inner Class

Anonymous inner class, that is, there is no name to initialize the class, and there is no need to save the instance to the variable.

Anonymous inner classes can create classes and interfaces anonymously

Topics: Java JavaSE