Java object oriented

Posted by hawnted on Sat, 22 Jan 2022 17:31:13 +0100

Java object oriented (V)

encapsulation

Goal of programming

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

Encapsulated information 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.

Key to packaging

  • Property: private

    private privatizes the property so that other programs cannot easily call the property

  • get/set:

    Provides methods that can manipulate private properties

  • Example 1:

    Set private properties in class Student and call out and assign get and set of these private properties

    method

    public class Student {
        //Property private (via private)
        //name
        private String name;
        //Student number
        private int id;
        //Gender
        private char sex;
        //Provide some methods that can manipulate this property
        //Some public get and set methods are provided
        //get gets this data
        public String getName(){
            return this.name;//Get the name attribute through getName()
        }
        public void setName(String name){
            this.name=name;//Assign a value to the name attribute through setName()
        }
    }
    
    

    In the main function, the set and get methods in the class are used to assign and call private attributes

    public class Application {
        public static void main(String[] args) {
            Student s1 = new Student();
            s1.setName("Shi Xiaopeng");//Assign a value to the name private property through setName() in the Student class
            System.out.println(s1.getName());//Get the private name attribute through getName() in the Student class
        }
    }
    //Output:
    Shi Xiaopeng
    
  • Example 2:

    Application of get/set

    For example, you can detect whether the data is legal

    Student class

    public class Student {
        //Property private (via private)
        //name
        private String name;
        //Student number
        private int id;
        //Gender
        private char sex;
        //Age
        private int age;
        //Provide some methods that can manipulate this property
        //Some public get and set methods are provided
        //get gets this data
        public String getName(){
            return this.name;//Get the name attribute through getName()
        }
        public void setName(String name){
            this.name=name;//Assign a value to the name attribute through setName()
        }
    
        public int getId() {
            return id;
        }
    
        public char getSex() {
            return sex;
        }
    
        public void setSex(char sex) {
            this.sex = sex;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            if(age>=0 && age<=100){
                this.age = age;
            }else{
                System.out.println("Illegal age");
            }
        }
    }
    
    

    Main function

    public class Application {
        public static void main(String[] args) {
            Student s1 = new Student();
            s1.setName("Shi Xiaopeng");//Assign a value to the name private attribute through setName() in the Student class
            System.out.println(s1.getName());//Get the private name attribute through getName() in the Student class
            //Enter an unlikely age
            s1.setAge(999);
            System.out.println(s1.getAge());
            //Enter a normal age
            s1.setAge(20);
            System.out.println(s1.getAge());
        }
    }
    //Output:
    Shi Xiaopeng
     Illegal age
    0
    20
    
    

Function of encapsulation

  • Improve program security and protect data
  • Implementation details of hidden code
  • Unified interface
  • System maintainability increased

inherit

The essence of inheritance

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

The key to inheritance

  • extands:

    Used for extension. A subclass is an extension of a parent class

  • Java has only single inheritance, not multiple inheritance

What is inheritance

  • Inheritance is a relationship between classes (relationship between classes: inheritance, dependency, composition, aggregation, etc.)

  • Inheritance relationship has two classes: one is a child class (derived class) and the other is a parent class (base class)

  • Subclasses inherit the parent class through extensions

  • Subclasses can override the methods of the parent class (modify the methods inherited by subclasses instead of)

  • Subclasses can inherit the methods of the parent class (example 1)

  • General subclasses inherit public methods and cannot inherit private (private) properties and methods (example 2)

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

  • Open inheritance tree: Ctrl+H

  • Example 1:

    • Create parent class

      //human beings
      //Parent class
      //Base class
      public class Person {
          public void say(){
              System.out.println("Said a word");
          }
      }
      
      
    • Create subclasses

      //Teacher class
      //Subclass
      //The subclass inherits all the methods of the parent class
      //Derived class
      //Successor to teacher (teacher is)
      public class Teacher extends Person{
      }
      
      
    • Main function application

      public class Application {
          public static void main(String[] args) {
              //Creating objects from subclasses
              Teacher teacher = new Teacher();
              //Because the subclass inherits from the parent class, the method subclass object of the parent class can be used directly
              teacher.say();
          }
      }
      //Output:
      Said a word
      
  • Example 2:

    • Parent class

      //human beings
      //Parent class
      //Base class
      public class Person {
          private int a=10;
          int b=10;
          public void say(){
              System.out.println("Said a word");
          }
          public void say1(){
              System.out.println(a);
          }
      }
      
    • Subclass

      //Teacher class
      //Subclass
      //The subclass inherits all the methods of the parent class
      //Derived class
      //Successor to teacher (teacher is)
      public class Teacher extends Person{
      }
      
    • Main function

      public class Application {
          public static void main(String[] args) {
              //Creating objects from subclasses
              Teacher teacher = new Teacher();
              //Because the subclass inherits from the parent class, the method subclass object of the parent class can be used directly
              teacher.say();
              System.out.println(teacher.b);
              teacher.say1();
          }
      }
      
      //Output:
      Said a word
      10
      10
      

Super

  • super refers to calling the parent class

  • If both the subclass and the parent class define an attribute with the same name. Then use the attribute name or this. In the subclass The attribute name calls all the attributes of the subclass, and super The attribute name calls the parent attribute (example 1)

  • The subclass constructor can call the constructor of the parent class

  • The subclass constructor calls the parameterless construction of the parent class by default (example 2)

  • The constructor that calls the parent class must be placed on the first line in the child class constructor (example 2)

  • The constructor that calls itself must be written on the first line (this() calls its own parameterless construct, this()) Call itself (parameterized construction)

  • super() calls the parameterless construction of the parent class, super (...) Call parent class parameterized construction

  • The constructor that calls the parent class and the constructor that calls itself cannot exist at the same time (because both are required to be written on the first line)

  • Because the default parameterless construction disappears after the parent class writes the parameterless construction, and because the subclass constructor calls the parameterless construction by default, once the parent class writes the parameterless construction, the subclass cannot write the constructor. Therefore, if the parent class wants to write a parameterized construct, it must add a parameterless construct or the child class calls the parameterless construct of the parent class (because the parent class writes a parameterless construct, there is no default parameterless construct, so if the parent class does not write a parameterless construct, the child class constructor will call the parameterless construct of the parent class by default, resulting in an error) (example 3)

  • Example 1:

    Parent class:

    //human beings
    //Parent class
    //Base class
    public class Person {
        String name = "father";
    }
    

    Subclass:

    //Student class
    //Subclass
    //The subclass inherits all the methods of the parent class
    //Derived class
    //Successor to student (student is)
    public class Student extends Person{
        String name = "son";
        public void say(){
            System.out.println(name);//Output subclass name attribute
            System.out.println(this.name);//Output subclass name attribute
            System.out.println(super.name);//Output parent class name attribute
        }
    }
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            Student student = new Student();
            student.say();
        }
    }
    //Output:
    son
    son
    father
    
  • Example 2:

    Parent class:

    //human beings
    //Parent class
    //Base class
    public class Person {
        String name = "father";
        int age;
        private int b;
        //Nonparametric construction method
        public Person(){
            age=19;
            b=20;
        }
    }
    
    

    Subclass:

    //Student class
    //Subclass
    //The subclass inherits all the methods of the parent class
    //Derived class
    //Successor to student (student is)
    public class Student extends Person{
        String name = "son";
        String sex ;
        public Student(){
            //Calling the constructor of the parent class must be written on the first line
            super();//By default, the parameterless construction is called, so super() does not need to be written. If it is written, it must be placed on the first line
            sex = "man";
        }
        public void say(){
            System.out.println(sex);
            System.out.println(age);
        }
    }
    
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            Student student = new Student();
            student.say();
        }
    }
    //Output:
    man
    19
    
  • Example 3:

    Parent class:

    //human beings
    //Parent class
    //Base class
    public class Person {
        String name = "father";
        int age;
        //Nonparametric construction method
        public Person(int age){
            this.age=age;
        }
    }
    

    Subclass 1:

    //Student class
    //Subclass
    //The subclass inherits all the methods of the parent class
    //Derived class
    //Successor to student (student is)
    public class Student extends Person{
        String name = "son";
        String sex ;
        public Student(int age){
            //Call the parameterized construct of the parent class
            super(age);//By default, the parameterless construction is called, and super() does not need to be written. If it is written, it must be placed in the first line
            sex = "man";
        }
        public void say(){
            System.out.println(sex);
            System.out.println(age);
        }
    }
    
    

    Subclass 2:

    //Teacher class
    //Subclass
    //The subclass inherits all the methods of the parent class
    //Derived class
    //Successor to teacher (teacher is)
    public class Teacher extends Person{
        public Teacher(){
            //Call the parameterized construct of the parent class
            super(50);
        }
    }
    
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            Student student = new Student(30);
            Teacher teacher = new Teacher();
            student.say();
            System.out.println(teacher.age);
        }
    }
    //Output:
    man
    30
    50
    
super and this
super notes:
  • 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
super VS this:
  • The objects represented are different:
    • This: call this object itself
    • super: represents the application of the parent object
  • Premise:
    • this: can be used without inheritance
    • super: can only be used under inheritance conditions
  • Construction method:
    • this(): the construction of this class (itself)
    • super(): Construction of parent class

rewrite

  • Rewriting is the rewriting of methods and has nothing to do with properties

  • There are great differences between static methods and non static methods (example 1, example 2)

  • Only those in dynamic methods are rewritten

  • Override shortcut: Alt+Insert: override

  • Example 1 (in static method):

    Parent class:

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

    Subclass:

    public class A extends B {
        //Class A overrides the test() method in the parent class
        //Static method
        public static void test(){
            System.out.println("A=>test()");
        }
    }
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            //Method is only related to the data type defined on the left
            A a = new A();
            a.test();
            //A reference to a parent class points to a child class
            B b = new A();
            b.test();
        }
    }
    //Output:
    A=>test()
    B=>test()//The subclass does not override the method of the parent class (because it is a static method)
    
  • Example 2 (Rewriting in dynamic methods):

    Parent class:

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

    Subclass:

    public class A extends B {
        //Class A overrides the test() method in the parent class
        public void test(){
            System.out.println("A=>test()");
        }
    }
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            //Method is only related to the data type defined on the left
            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();
        }
    }
    //Output:
    A=>test()
    A=>test()//The subclass overrides the method of the parent class
    

Rewriting considerations:

  • 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 (not reduced): public > protected > Default > private

    For example, if the method in the parent class is Default, the subclass can override the method to public or Protected (expanded)

  • Thrown exception: the range can be narrowed but not expanded: classnotfoundexception -- > exception (large)

Reason for rewriting:

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

polymorphic

  • Polymorphism enables dynamic compilation: Type: extensibility

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

    give an example:

    //Parent class Person(), child class Student()
    Student s1 = new Student();//new Student() is the actual type of the object (determined)
    //The reference type that can be pointed to is uncertain, and the reference of the parent class points to the child class
    Person s2 = new Student();//Person is a reference type
    Object s3 = new Student();
    
  • When the reference of the parent class points to the child class, if the parent class method is overridden in the child class, the called method is the child class method; If not overridden, the method called is a parent method

    Example 1 (rewritten):

    Parent class:

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

    Subclass:

    public class A extends B {
        //Class A overrides the test() method in the parent class
        public void test(){
            System.out.println("A=>test()");
        }
    }
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            //Method is only related to the data type defined on the left
            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();
        }
    }
    //Output:
    A=>test()
    A=>test()//The subclass overrides the method of the parent class
    

    Example 2 (not rewritten):

    Parent class:

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

    Subclass:

    public class A extends B {
    }
    
    

    Main function:

    public class Application {
        public static void main(String[] args) {
            //Method is only related to the data type defined on the left
            A a = new A();
            a.test();
            //A reference to a parent class points to a child class
            B b = new A();
            b.test();
        }
    }
    //Output:
    B=>test()
    B=>test()
    
  • Let a be the parent method and B be the child method, after A b = new B(); After the parent refers to a reference, the method a.say() is called:

    • If A (parent class) does not have A say() method and B (child class) has A say() method, the say() method cannot be called;

    • If A has A say() method and B does not override the say() method, call A's say() method;

    • If A has A say() method but B overrides the say() method, B's say() method will be called;

  • Let a be the parent method, B be the child method, and B = new b(); After subclass points to reference, call method a.say():

    • If A (parent class) has no say() method and B (child class) has A say() method, call B's say() method;

    • If A has A say() method and B does not override the say() method, call A's say() method;

    • If A has A say() method but B overrides the say() method, B's say() method will be called;

  • To sum up:

    • The methods that can be called by a subclass are their own or inherit from the parent class
    • A parent class can point to a subclass (can call methods overridden by subclasses), but cannot call methods unique to subclasses

Precautions:

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

  • Parent and child classes are related, (parent-child type conversion exception: ClassCastException)

  • Conditions for polymorphism:

    1. There is an inheritance relationship
    2. Method needs to be overridden
    3. A parent class reference points to a child class object
  • Overridden is not supported:

    1. static method: belongs to class, not instance
    2. final constant:
    3. Private method: private method