2 object oriented advanced

1, Encapsulate private

  • In development, in order to avoid logic errors, we suggest encapsulating all properties and providing setter and getter methods for setting and obtaining operations

2, static

  • Static means "static" and can be used to modify member variables and member methods
  • The main function of static is to create domain variables or methods independent of specific objects
    Simple understanding: the method or variable modified by the static keyword does not need to rely on the object for access. As long as the class is loaded, it can be accessed through the class name. And it will not create multiple copies of data in memory because of multiple creation of objects.
  • Popular explanation: static belongs to the class and is managed directly. If you reference a static method or variable, you don't need to new a new object, you can directly use the class. Variable / method
  • In addition, in writing code, it is convenient to abbreviate the constant quantity in the program
    For example, if people working in Beijing work in Beijing, the object can be written in a static area for convenience. It is agreed to modify it without changing it step by step

a key:

  • Static members are loaded and initialized when the class is loaded.
  • No matter how many objects exist in a class, there is always only one static attribute in memory (which can be understood as common to all objects)
  • When accessing: static cannot access non static, non static can access static!
    Popular explanation: you only exist after your father and your mother get married. Your mother can't find you before marriage, but with you after marriage, you can find your mother no matter what step you take (you are non static, your mother is static)

3, Code block

  • Common code block
    The code blocks that appear in the executed process are called ordinary code blocks.

  • Construct a code block (a code fragment that does not have any prefix or suffix in the class and is enclosed by "{}")
    A member code block in a class, which we call a construction code block, is executed every time an object is created and before the construction method.

  • Static code block
    The member code block decorated with static in the class, which we call static code block, is executed when the class is loaded. Every time the program is started to close, only
    A block of code that is executed once.

  • Synchronous code block

  • Interview questions:
    Construction method and execution sequence of construction code block and static code block:
    Static code block -- > construction code block -- > construction method

4, Permission modifier

  • Public: represents public content, which can be called by all operations

5, Inherit

  • Inheritance is that a subclass inherits the characteristics and behavior of the parent class, so that the subclass object (instance) has the instance domain and method of the parent class, or the subclass inherits the method from the parent class, so that the subclass has the same behavior as the parent class.

Generally speaking, you can have all the characteristic behaviors your father has. But you can have a new characteristic foundation based on these characteristic behaviors your father gave you. When applied to the code, the subclass can call the properties and methods of the parent class through inheritance (the advantage is to reduce the repeatability of the code)

public class Demo5 {
    public static void main(String[] args) {
       Student student = new Student();
        student.setName("Qiao Yicheng");
        student.getAge(18);
        student.say();
    }
  }
    class Person{
        private String name;
        private int age;

        public Person() {
        }

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

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

        public int getAge(int i) {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }
        public void say(){
            System.out.println("I am:"+name+",I this year"+age+"Years old");
        }
    }
    
     class Student extends Person{

    }

  • Inheritance limitation: Java has only single inheritance, not multiple inheritance. That is, if you want to inherit multiple, you should sort them one by one, inherit the previous one, and the last one inherits the complete one.

Subclass instantiation:
It is the subclass that gets the address of the parent class
Note the permission modifier: public protected can be used in parent and child classes

6, super

  • Through super, you can access the construction methods, properties and methods of the parent class.
  • The code calling the super constructor must be written on the first line of the subclass constructor

super is often found automatically without parameters, and can also be omitted. super can also pass parameters

7, The difference between rewriting and overloading

  • Rewrite: when a subclass inherits the parent class, the subclass has the option to rewrite its own method
  • Rewrite rule:
    1. The parameter list must be exactly the same as the rewritten method
    2. The type of the return value must be exactly the same as that of the overridden method
    3. The access permission cannot be lower than that of the overridden method in the parent class
    4. Member methods of a parent class can only be overridden by its subclasses
    5. Methods declared as static and private cannot be overridden, but can be declared again
public class Demo5 {
    public static void main(String[] args) {
       Student student = new Student();
              student.say();
    }
}

    class Person{
        public void say(){
            System.out.println("I am a human");
        }
    }

     class Student extends Person{
         public void say(){
            System.out.println("I am a student of mankind");
}
    }
    ------------------------------------------------------
                     I am a student of mankind

The parameter list must be exactly the same as the overridden method
If the parent class does not pass parameters, but the child class passes parameters, the method of the parent class is still called

public class Demo5 {
    public static void main(String[] args) {
       Student student = new Student();
              student.say();
    }
}

    class Person{
        public void say(){
            System.out.println("I am a human");
        }
    }

     class Student extends Person{
         public void say(String test){
            System.out.println("I am a student of mankind");
}
    }
    -----------------------------------------------------
                      I am a human
  • The difference between Override and Overload:
    1. Location of occurrence:
    Overloading: in a class
    Overrides: in child parent classes
    2. List limit of parameters:
    Overload: must be different
    Override: must be the same
    3. Return value type:
    Overload: independent of return value type
    Override: return value types must be consistent
    4. Access rights:
    Overload: independent of access rights
    Override: the access permission of the child cannot be lower than that of the parent
    5. Exception handling:
    Overload: independent of exception
    Rewrite: the exception range can be reduced, but new exceptions cannot be thrown

8, final

  • final keyword is used to modify attributes and variables
    After modification, the variable becomes a constant and cannot be assigned a value
  • public static final: this constant can be used anywhere
  • final keyword modifier class
    Cannot be inherited
  • final keyword modification method
    Cannot be overridden by subclasses

9, Abstract class

Popular explanation: if people are regarded as the largest parent class and compared to abstract classes, one of the behaviors is that people can speak. But people can be divided into many kinds: students, nurses and sheriffs. Everyone can speak, but what they say is different. For everyone, what they say will be specific. But for people's Congress, speaking contains too much Multi is relatively abstract and vague. When subclasses want to clarify what they say, it is materialization.

  • There are several principles in the use of abstract classes:
    Abstract classes themselves cannot be instantiated directly, that is, they cannot be instantiated directly with the keyword new.
    An abstract class must be inherited by subclasses, and the inherited subclasses (if not abstract classes) must override (override) all abstract methods in the abstract class.
public class Demo5 {
    //Format:
   abstract class Person{
       //Note that abstract methods are only declared but not implemented, that is, they are not followed by braces
       public abstract void say();//{
       
       // }
   }
    }

public class Demo5 {
 
   abstract class Person{
       public abstract void say();
   }
   //1. Subclasses inherit abstract classes, or add abstract before the class name
   public abstract class Student extends Person{
       
   }
   //2. Or rewrite methods, that is, materialize abstract classes
    public class Nurse extends Person{
       
       public void say() {
           
       }
   }
    }

  • common problem
    1. Can abstract classes use final declarations?
    No, because the final modified class cannot have subclasses, and the abstract class must have subclasses to be meaningful, so it cannot.
    2. Can an abstract class have a constructor?
    There can be construction methods, and the process of subclass object instantiation is the same as that of ordinary class inheritance. It is necessary to call the construction method in the parent class (parameterless by default), and then call the subclass's own construction method. (construction methods cannot be created by programmers, but can be created by Java virtual machine)
public class Demo5 {


    abstract class Person {
        public Person() {
            System.out.println("This is the construction method");
        }

        public abstract void say();
    }

    public class Student extends Person {
        @Override //This is an overridden annotation to check whether there are methods in the parent class
        public void say() {
            System.out.println("I am a student");
        }
    }

    public class Nurse extends Person {
        public void say() {
            System.out.println("I'm a nurse");
        }
    }

}

  • The difference between abstract classes and ordinary classes
    1. The abstract class must be decorated with public or protected (if it is private, the subclass cannot inherit and cannot implement its abstract methods). The default is public
    2. Abstract classes cannot use the new keyword to create objects, but when subclasses create objects, the abstract parent class will also be instantiated by the JVM.
    3. If a subclass inherits an abstract class, it must implement all its abstract methods. If there are unimplemented abstract methods, the subclass must also be defined as an abstract class

10, Interface

  • Purpose:
    Reduce program coupling
    Easy program expansion
    It is conducive to the maintenance of the procedure
  • Interfaces can only be abstract classes (abstract classes can include abstract classes and entity classes) or global constants

The interface cannot have implementable content, which means it cannot have curly braces

//Format:
    interface Interface name{
        Global constant ;
        Abstract method ;
}
  • Because the interface itself is composed of global constants and abstract methods, the member definitions in the interface can be abbreviated as:
    1. When writing global constants, you can omit the public static final keyword, for example:
    public static final String INFO = "content";
    After abbreviation:
    String INFO = "content";
    2. When writing abstract methods, you can omit the public abstract keyword, for example:
    public abstract void print() ;
    After abbreviation:
    void print() ;
public interface Demo6 {
    int a = 10;//public static final int a = 10;
    String b ="123";//public static final String b = "123"
    void say();//public abstract void say(); cannot add {}
}

  • Interfaces can be implemented in multiple ways:
    Format:
    class subclass implements parent interface 1, parent interface 2{
    }
    The above code is called the implementation of the interface. If a class wants to implement the interface and inherit the abstract class, it can be written in the following format:
    Class subclass extends, parent class implements, parent interface 1, parent interface 2{
    }

  • Because interfaces are abstract parts and there is no specific implementation, multiple inheritance is allowed, for example:
    interface C extends A,B{
    }

  • If an interface is to be used, it must rely on subclasses. Subclasses (if not abstract classes) implement all abstract methods in the interface.

  • Difference between interface and abstract class:
    1. Abstract classes should be inherited by subclasses, and interfaces should be implemented by classes.
    2. Interfaces can only declare abstract methods, and abstract classes can declare abstract methods or write non abstract methods.
    3. The variables defined in the interface can only be public static constants, and the variables in the abstract class are ordinary variables.
    4. Abstract classes use inheritance and cannot inherit more. Interfaces use implementation and can be implemented more
    5. Static methods can be included in abstract classes, but not in interfaces (static methods cannot be overridden by subclasses, so static methods cannot be declared in interfaces)
    6. An interface cannot have a constructor, but an abstract class can

11, Polymorphism

  • Polymorphism: it refers to various forms of expression of objects (multiple forms)
  • Popular explanation: take people as the parent class, and the child class can be nurses, students, etc. this concept is called polymorphism.
  • The concept of object polymorphism is very easy to understand. There are subclasses and parent classes in classes. Subclasses are a form of parent classes, from which object polymorphism comes.
    ps: method overloading and rewriting are also polymorphic, but they are polymorphic (multiple forms of the same method name).
    Overloading: the embodiment of the polymorphism of methods in a class
    Rewriting: the polymorphism of methods in child and parent classes.
  • Use of polymorphism: object type conversion
    Conversion similar to basic data type:

    ·Upward Transformation: change a child class instance into a parent class instance
    |-Format: parent class, parent class object = child class instance;

    ·Downward Transformation: change the parent class instance into a child class instance
    |-Format: subclass subclass object = (subclass) parent class instance

public interface Person {
    void say();//public abstract void say(); cannot add {}
}
public class Student implements Person{
    @Override
    public void say() {
        System.out.println("I am a student");
    }
public class Teacher implements Person{
    @Override
    public void say() {
        System.out.println("I'm a teacher");
    }
public class Demo5 {
    //A parent class reference points to a child class
    public static void main(String[] args) {
        Student student = new Student();
        Teacher teacher = new Teacher();

        Person person1 = student;  //Call a student a man
        Person person2 = teacher;  //Call the teacher a man
        person1.say();
        person2.say();
        
        Student student1 = (Student) person1;//Call people students, and turn from parent to child
        //Students cannot be called teachers
        student1.say();
    }
    -----------------------------------------------------
    I am a student
    I'm a teacher
    I am a student
public class Demo5 {

    public static void main(String[] args) {
        Student student = new Student();
        student.say();
        Teacher teacher = new Teacher();
        teacher.say();
    }
//When we are writing a new program, the code of 12-14 can fuzzify the person parent class without moving. Whether we want students or teachers to give us or we want new tasks, it can be rewritten directly, which is more convenient
    public static void say(Person person){
        person.say();
        -------------------------------------
          I am a student
          I'm a teacher
    }
}

12, instanceof

  • effect:
    To determine whether an object is an instance of a specified class, you can use the instanceof keyword
    Prevent teachers from being described as students or students from being described as teachers for early judgment
  • Format:
    Instantiate the object instanceof class. / / this operation returns boolean data

13, Inner class

  • In Java, a class can be defined in another class or a method. Such a class is called an inner class

  • Internal classes can be divided into 4 types:
    1. Member inner class
    2. Local inner class
    3. Anonymous inner class
    4. Static inner class

  • Member inner class
    Features: the inner class of a member can unconditionally access all member properties and member methods of the outer class (including private members and static members).
    When the internal class of a member has a member variable or method with the same name as the external class, it will be hidden. That is, by default, the members of the internal class of the member are accessed. If you want to access the members of the external class with the same name, you need to access them in the following form:
    External class. this. Member variable
    External class. this. Member method

public class Demo6 {
    //External class
    public static class Outer{
        private int a =10;
        private int b =20;
        public int getA() {
            return a;
        }

        public void setA(int a) {
            this.a = a;
        }

        //Inner class
        class Inner{
            private int a = 30;

            public  void say(){
                System.out.println(a);//If the inner class and the outer class have one attribute at the same time, the nearest one is the attribute of the inner class
                System.out.println(Outer.this.a);//Print the format of the external class
                System.out.println(b);//The internal class can directly use everything of the external class. The conceptual order is that the internal class exists only after all the attributes of the external class are created
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        Demo6.Outer o = new Demo6.Outer();
        Demo6.Outer.Inner i = o.new Inner();
        i.say();
    }
}
------------------------------------------------------------
30
10
20

  • Local inner class
    A local internal class is a class defined in a method or scope. The difference between it and a member internal class is that the access of a local internal class is limited to the method or scope.

A local internal class is like a local variable in a method. It cannot have public, protected, private and static modifiers.

public class Demo7 {
    //method:
    public static void main(String[] args) {

        //Local inner class
        class PersonImp implements Person{

            @Override
            public void say() {
                System.out.println("I am a local inner class, and my parent class is Person");
            }
        }

        PersonImp personImp = new PersonImp();
        haha(personImp);
    }


    //When we want to write something new, but its parent class is person, and this method only needs to be called once, we can implement it through the local internal class
    public static void haha(Person person){

    }
}

  • Anonymous Inner Class
    Without a name, you usually don't use it for the second time
public class Demo7 {
    //method:
    public static void main(String[] args) {

        //Anonymous Inner Class 
     Person person = new Person() {

       public void say(){
           System.out.println("I am an anonymous inner class");
       }

       };
      haha(person);
     }

    public static void haha(Person person){

    }
    
}

  • In the process of using anonymous inner classes, we need to pay attention to the following points:
    1. When using anonymous inner classes, we must inherit a class or implement an interface, but we can't have both. At the same time, we can only inherit one class or interface
    The designer implements an interface.
    2. Constructors cannot be defined in anonymous inner classes.
    3. No static member variables or static methods can exist in an anonymous inner class.
    4. Anonymous inner classes are local inner classes, so all restrictions on local inner classes also apply to anonymous inner classes.
    5. Anonymous inner classes cannot be abstract. They must implement all abstract methods of inherited classes or implemented interfaces.
    6. Only local variables of type final can be accessed

  • Static inner class
    For a class defined in another class, the keyword static is added in front of the class.
    Static inner classes do not need to depend on external class objects, which is similar to the static member properties of classes, and it cannot use non static member variables or methods of external classes

public class Test {
    public class Book{
        private String name = "123";
        private static int a = 1;
        //Static inner class
        static class Infor{
            public void say(){
                //The static inner class can access the static a, but cannot access the name
                System.out.println("I'm a static inner class");
            }
        }
    }
    public static void main(String[] args) {
          Book.Infor infor = new Book.Infor();
          infor.say();
    }
}

14, Exception handling

  • The Exception refers to the Exception class. There is a parent class Throwable (possible throw) in Java
    Throwable has two subclasses:
    1.Error: indicates an error. It is an error operation sent by the JVM. It can only be avoided as far as possible and cannot be handled by code.
    2.Exception: generally refers to errors in all programs, so try... catch is generally handled in the program.

  • Exceptions fall into two categories:
    1. Checked exception: if there is an error in writing, it will turn red
    2. Unchecked exception: no prompt will be given when writing, but an error will be reported when running
  • Basic format and concept of exception handling
     try {
           //Code snippet with possible exception
        }catch(Exception type 1 object name 1){
           //Exception handling
        }catch (Exception type 2 object name 2){
            //Exception handling operation 2   
        } finally {
            //Exception unified processing exit that must be executed
            //finally must be executed regardless of whether an exception occurs
        
        }
    }
  • It can be seen that the divisor cannot be 0, otherwise there will be exceptions, so we should judge the exceptions for possible problems.
   public static void main(String[] args){

        haha();
        System.out.println("Program execution completed , Normal end");
    }

    private static void haha() {
        try {
            Scanner input = new Scanner(System.in);
            System.out.println("Please enter a number");
            int x = input.nextInt();
            System.out.println("Please enter another number");
            int y = input.nextInt();
            System.out.println(x / y);
            System.out.println("Processing completed");
        }catch(Exception e){//polymorphic
            System.out.println("Incorrect input");
        }finally {
            //Exception unified processing exit that must be executed
            //finally must be executed regardless of whether an exception occurs
            System.out.println("213123");
        }
    }
}
  • Sequence of exception checking
    At the beginning, the ontologies of various methods should find the second. If it is clear that there is an error, deal with it by themselves. If the corresponding method does not deal with it, deal with it by the function calling the method. If it does not deal with it, it will be fed back to the JVM. Because he is the boss, he finds the error at the beginning, and he also asks the program to solve it by itself. If it does not deal with it, he will report an error.
  • Type of exception
    You can find it through JDK, but you can't find the specified. We usually use the RuntimeException with the largest range to handle exceptions.

  • Interview questions

  1. Which part of try catch finally can be omitted?
    A: catch and finally can be omitted. Catch and finally cannot be omitted at the same time
    Note: it is allowed to omit catch blocks in format, but exceptions will not be caught when exceptions occur, and we will not write code in this way in development
  2. In try catch finally, if the catch return s, will finally execute?
    A: the code in finally will execute
    Detailed explanation:
    Execution process:
    1. First calculate the return value, store the return value, and wait for the return
    2. Execute finally code block
    3. Return the previously stored return value;

Note:

  1. The return value is determined before the finally operation and cached. No matter what changes are made to the value by finally, the returned value is not valid
    Will change
  2. finally, it is not recommended to include return in the code, because the program will exit in advance in the above process, that is, the returned value is not try or
    Value in catch
  3. If the JVM is stopped in try or catch, finally will not execute. For example, power failure --, or exit through the following code
    JVM:System.exit(0);

Keywords: Java

Added by jbreits on Mon, 25 Oct 2021 10:51:20 +0300