Object oriented review

Keywords: Java

;

object-oriented

1. What is object-oriented

  • Object oriented programming OOP
  • Essence: organize code in the form of classes and organize (encapsulate) data in the form of objects
  • abstract
  • Three characteristics: encapsulation, inheritance and polymorphism

2. Relationship between class and object

  • Class is an abstract data type. It is the overall description / definition of a certain type of transaction, but it cannot represent a specific transaction
    • For example, the Person class represents all people and the Car class represents all cars. These are used to describe or define the characteristics and behaviors that a specific transaction should have
  • Objects are concrete instances of abstract concepts
    • For example, Zhang San is a specific example of the Person class, and the BMW he drives is a specific example of the Car class

3. Create and initialize objects

3.1 create an object using the new keyword

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

Test case:

Student:

	//Student class
public class Student {
    //Properties: Fields
    String name;
    Integer age;

    //method
    public void study(){
        System.out.println(this.name+"I am learning");
    }
}

Test:

/**
 * Test class
 * Only one main method should exist in a project
 */
public class Test {
    public static void main(String[] args) {
        //Class is abstract and needs to be instantiated
        //After class instantiation, it will return its own object
        Student student = new Student();

        student.name = "Zhang San";
        student.age = 18;

        System.out.println(student.name);
        System.out.println(student.age);

        student.study();
    }
}

Operation results:

Zhang San
18
 Zhang San is studying

3.2 constructor

Constructors in classes, also known as construction methods, must be called when creating objects. Constructors have two characteristics:

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

effect:

  • The essence of new is to call the constructor
  • Initializes the value of the object

Note:

  • After defining a parameterized construct, if you want to use a parameterless construct, define a parameterless construct to be displayed

Test case:

Person

public class Person {
    String name;

    /**
     *  A class will have a parameterless constructor even if it doesn't write anything
     *  Instantiation initial value
     *  1.Using the new keyword is essentially calling the constructor
     *  2.Used to initialize
     */
    // Display definition constructor, which is a default constructor
    public Person(){
    }

    /**
     *  Parametric structure
     *  Once a parameterized construct is defined, a nonparametric construct must display the definition
     */
    //Equivalent to heavy load
    public Person(String name){
        this.name = name;
    }
}

Test

public class Test {
    public static void main(String[] args) {
        Person person = new Person();		//Call parameterless construction
        Person person1 = new Person("Zhang San"); //Call parameterized construction
        System.out.println(person.name);
        System.out.println(person1.name);
    }
}

Operation results:

null
 Zhang San

4. Packaging

  • Encapsulation (hiding of attributes)

    • Generally, direct access to the actual display of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding
  • Programming should pursue "high cohesion and 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

advantage:

  • Improve program security and protect data
  • Implementation details of hidden code
  • Unified interface
  • The maintainability of the system is improved

Student

/**
 * Class private: private
 */

public class Student {

    //Property private
    private String name;
    private Integer id;
    private String sex;
    private Integer age;


    //Provide methods that can manipulate this property
    //Get get value set setting value
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        if (age > 120 || age < 0) { //wrongful
            this.age = age;
        }else {
            age = 18;
        }

    }
}

Test

public class Test {
    public static void main(String[] args) {
        Student student = new Student();
        student.setName("Zhang San");
        student.setId(1);
        student.setSex("male");

        student.setAge(130);
        System.out.println(student.getName());
        System.out.println(student.getAge());
    }
}

Operation results:

Zhang San
18

5. Succession

5.1 understanding of inheritance

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

  • Extensions means extensions. A subclass is an extension of a parent class.

  • java classes only have single inheritance, not multiple inheritance!

  • Inheritance is the relationship between classes, as well as 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). The subclass inherits from the parent class, which is represented by extensions.

  • In Java, all classes inherit the Object class directly or concisely by default

Person

//Person: parent class
public class Person {
    public void people(){
        System.out.println("Everyone is human");
    }
}

Chinese

//Chinese: subclass
public class Chinese extends Person{

}

Test

public class Test {
    public static void main(String[] args) {
        //The parent class inherited by the subclass will have all its methods
        Chinese chinese = new Chinese();
        chinese.people();//Everyone is human
    }
}

5.2 super explanation

Person

//Person: parent class
public class Person {
    public Person() {
        System.out.println("person No parameter execution");
    }

    protected String name = "Zhang San";

    public void print(){
        System.out.println("person");
    }
}

Chinese

//Chinese: subclass
public class Chinese extends Person{
    private String name = "Li Si";

    public Chinese() {
        /**
         * super();Hidden code, calling the parameterless construction of the parent class
         * Must be in the first line of the subclass
         */
        System.out.println("chinese No parameter execution");
    }

    public void print(){
        System.out.println("chinese");
    }

    public void test(String name){
        System.out.println(name);       //Wang Wu
        System.out.println(this.name);  //Li Si
        System.out.println(super.name); //Zhang San
    }

    public void test1() {
        print();       //chinese
        this.print();  //chinese
        super.print(); //person
    }
}

Test

public class Test {
    public static void main(String[] args) {
        Chinese chinese = new Chinese();
        System.out.println("=============");
        chinese.test("Wang Wu");
        System.out.println("=============");
        chinese.test1();
    }
}

Operation results:

person No parameter execution
chinese No parameter execution
=============
Wang Wu
 Li Si
 Zhang San
=============
chinese
chinese
person

Summary:

super note:

  • super calls the constructor of the parent class, which must be placed first in the constructor
  • super must only appear in subclass methods or constructor methods
  • super and this cannot call constructor at the same time

super and this:

  • Different representative objects:
    • this: the object itself is the caller
    • super: represents a reference to a parent object
  • Premise:
    • this: can be used without inheritance
    • super: can only be used under inheritance conditions
  • Differences in construction methods:
    • this(); Construction of this class
    • super(); Construction of parent class

5.3 method rewriting

  • 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
    • Modifier: the scope can be expanded but not reduced (public > protected > Default > privilege)
    • Exception thrown: the scope can be reduced, but not expanded
  • When overridden, subclass methods and superclasses must always be overridden; Method body is different!
  • Why rewrite?
    • The functions of the parent class and the child class are not necessarily required or satisfied

A

//Succession B
public class A extends B{
    //rewrite
    @Override
    public  void test(){
        System.out.println("A");
    }
}

B

//Rewriting is the rewriting of methods and has nothing to do with properties
public class B {
    
    public  void test(){
        System.out.println("B");
    }
}

Test

public class Test {

    public static void main(String[] args) {
        //Static method: the method call is only related to the data type defined on the left
        //Non static: you can choose to override

        A a = new A();
        a.test();
        //A reference to a parent class points to a child class
        B b = new A();//The subclass overrides the method of the parent class
        b.test();
    }
}

Operation results:

A
A

6. Polymorphism

6.1 understanding of polymorphism

  • The same method can take 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 an object
  • Conditions for polymorphism:
    • There is an inheritance relationship
    • Subclass overrides parent method
    • A parent class reference points to a child class object
  • Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes!

Person

public class Person {
    public void run(){
        System.out.println("person");
    }
}

Student

public class Student extends Person{
    @Override
    public void run() {
        System.out.println("student");
    }

    public void eat(){
        System.out.println("eat");
    }
}

Test

public class Test {
    public static void main(String[] args) {
        /**
         * The actual type of an object is determined
         * new Student();
         * new Person();
         */

        //The type of reference that can be pointed to is uncertain: the reference of the parent class points to the child class
        //The methods that students can call are their own or inherit the parent class
        Student s1 = new Student();
        //Person can point to subclasses, and it is not allowed to call methods unique to subclasses
        Person s2 = new Student();
        Object s3 = new Student();

        s2.run();//The subclass overrides the method of the parent class and executes the method of the subclass
        s1.run();

        //The methods that can be executed by an object mainly depend on the types on the left of the object, but the types on the right have little to do with it
        s1.eat();
//      s2.eat();
        ((Student)s2).eat();//Strong rotation
    }
}

Operation results:

student
student
eat
eat

matters needing attention:

  • Polymorphism is the polymorphism of a method, and there is no attribute
  • The parent and child classes are connected. If not, the type will be converted to an exception! ClassCastException
  • Existence conditions: inheritance relationship, method needs to be rewritten, and the reference of the parent class points to the child class object!

Cases that cannot be overridden:

  • static method belongs to class, but it does not belong to instance

  • final is a constant. final modified cannot be overridden

  • Private method: private and cannot be overridden

6.2 instanceof keyword and type conversion

  • Instanceof (type conversion), refers to the type, and judges what type an object is
//Create a Student class and Teacher class to inherit the Person class
public class Test {
    public static void main(String[] args) {
        //Object > Person > Student
        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
        //Object > Person > Teacher
        System.out.println(object instanceof Teacher);//false
        //Object > String
        System.out.println(object instanceof String);//false

        System.out.println("=====================");

        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

        System.out.println("=====================");

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

    }
}
//Person
public class Person {
    public void run(){
        System.out.println("person");
    }
}

//Student
public class Student extends Person {
    public void go() {
        System.out.println("student");
    }
}

//Test
public class Test {
    public static void main(String[] args) {
        //Type conversion
        Person obj = new Student();

        //Student convert this object to student type, and you can use the method of student type
        //person.go();
        ((Student)obj).go();//Output: student
    }
}

7. Static keyword

Non static methods can call non static methods, and static classes will be loaded directly

Student

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

    public void run(){
        go();//Non static methods can call non static methods
    }
    public static void go(){

    }

    public static void main(String[] args) {
        Student s1 = new Student();

        System.out.println(Student.age);
//        System.out.println(Student.score);  report errors
        System.out.println(s1.age);
        System.out.println(s1.score);


        new Student().run();
        go();
    }
}

Person

public class Person {

    //Assign initial value
    {
        System.out.println("Anonymous code block");
    }
    //Execute only once
    static {
        System.out.println("Static code block");
    }

    public Person() {
        System.out.println("Construction method");
    }

    public static void main(String[] args) {
        Person person1 = new Person();
        System.out.println(person1);
        System.out.println("====================");
        Person person2 = new Person();
        System.out.println(person2);
    }
}
/**
Static code block
 Anonymous code block
 Construction method
com.banyuan.demo07.Person@7c30a502
====================
Anonymous code block
 Construction method
com.banyuan.demo07.Person@49e4cb85
 */

Test (new feature)

//Static import package
import static java.lang.Math.random;
import static java.lang.Math.PI;

public class Test {
    public static void main(String[] args) {
        System.out.println(random());
        System.out.println(PI);
    }
}

8. Abstract class

  • Abstract modified methods are abstract methods and modified classes are abstract classes
  • Abstract classes can have no abstract methods, but classes with abstract methods should be declared as abstract classes at all
  • An abstract class cannot use the new keyword to create an object. It is used to allow subclasses to 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

B

public abstract class B {

    //Constraint someone to help us achieve
    //Abstract method, only method name, no method implementation
    public abstract void A();
    /**
     * 1.You can't use the new object class, you can only rely on subclasses to implement it; Constraints!
     * 2.Ordinary methods can be written in abstract classes
     * 3.Abstract methods must be written in abstract classes
     */
}

A

//All methods of an abstract class that inherit its subclasses must implement its methods, unless the subclass itself is abstract
public class A extends B {
    @Override
    public void A() {

    }
}

9. Interface

Common class: only concrete implementation

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

Interface: specification only

  • Keywords: interface

UserService

//Key words: interface and interface need to implement classes
public interface UserService {
    //All definitions in the interface are actually abstract. The default is public abstract
    void add(String name);

    void delete(String name);

    void update(String name);

    void query(String name);

    //Constant default: constants are generally not written in the public static final interface
    Integer age = 99;
}

TimeService

public interface TimeService {
    void timer();
}

UserServiceImpl

//Implementation class
//If you implement the class of the interface, you need to rewrite the methods in the interface
//Multiple implementations. java only has single inheritance, but can be implemented with multiple interfaces
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() {
    }
}

Summary:

  • effect:
    • Constraints!
    • Define some methods for different people to implement
    • Methods are public abstract constants by default, and public static final by default
    • The interface cannot be instantiated. There is no constructor in the interface
    • Interfaces can implement multiple
    • Implementing an interface must override the methods in the interface

10. Internal class

  • An internal class is to define another class within a class. For example, if a class a defines a class B, then class B is an internal class relative to class A
  • Member inner class

Outer

public class Outer {
    private Integer 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 void getOut(){
            Outer.this.out();
        }
    }
}

Test

public class Test {
    public static void main(String[] args) {
        Outer outer = new Outer();
        //Instantiate the inner class through the outer class, and the inner class of the member
        Outer.Inner inner = outer.new Inner();
        inner.in();
        inner.getID();
        inner.getOut();
    }
}

result:

This is the method of the inner class
10
 This is the method of an external class
  • Static inner class
public class Outer {
    private Integer 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");
        }
}

External id cannot be called because static is executed before id

  • Local inner class
public class Outer1 {
    //Local inner class
    public void B(){
        class C{

        }
    }
}
  • Anonymous Inner Class
public class Outer2 {
    public static void main(String[] args) {
        //There is no name to initialize the class, so there is no need to save the instance to the variable
        new Apple().eat();
        //Class that implements the interface
        new UserService(){

            @Override
            public void hello() {
                
            }
        };
    }
}
class Apple {
    public void eat(){
        System.out.println("Eat apples");
    }
}

interface UserService{
    void hello();
}

Posted by Kano on Sun, 05 Sep 2021 19:12:45 -0700