java basics | complex classes and objects

Keep creating and accelerate growth! This is my 15th day participating in the "Nuggets Daily New Plan·October Update Challenge", click to view event details

Complex classes and objects

In Java object-oriented programming, developers can use the inheritance mechanism to organize and design classes in various application systems. - advantage:

  1. This improves the abstraction level of the program and is in line with human thinking.
  2. Improve software development efficiency and reduce maintenance workload
  3. Reduces code coupling

inherit

Inheritance is divided into single inheritance and multiple inheritance. -Single inheritance: means that the subclass (derived class) has only one parent class (superclass). This inheritance relationship is single and is a simple tree structure. - Multiple inheritance: A class has at least one parent class, which is a slightly complex network structure.

But for java, it only supports single inheritance, which is also for security reasons. - The syntax format is as followsjava /* public class 子类A [extends 父类B]{ ... } */ public class Student extend Person{ //... }

Derived class constructor

  • When creating a derived class object, the constructor of the derived class first calls the constructor of the superclass (parent class), and then executes the statements in the derived class constructor to initialize the new members of the derived class.
  • In the derived class constructor, you can use superthe method to call the superclass constructor. The statement calling the super method should be the first statement of the subclass constructor.
  • Format of calling super method:

java super(参数列表); Note: The parent class must define a constructor with a corresponding parameter list - if the constructor of the derived class does not call the constructor of the super class through the super method, and the super class does not have a method with formal parameters. Then Java first automatically calls the default construction method of the super class, which is responsible for initializing the super class data members. Otherwise, the compilation system will think that there is a syntax error. - If the super class defines a constructor with a formal parameter list, the derived class should define the first statement of the constructor with formal parameters to call super with formal parameters, so that the parameters can be passed to the super class constructor, ensuring Superclasses can initialize their own data members.

  • Code example ```java public class Parent{ String name; public Parent(){ System.out.println("Calling the default parent class"); name=new String("Unknown");

    }

}

Guess you like

Origin blog.csdn.net/y943711797/article/details/132972173