Classes and objects

There are five types of structures in the class. The following five types of structures are introduced in detail.

1. Object-oriented versus procedural

  • Process-oriented: Emphasizes functional behavior, takes function as the smallest unit, and considers how to do it.
  • Object orientation: Emphasize objects with functionality, class/object as the smallest unit, and consider who does it. — Materialism (Material determines consciousness)

2. The relationship between classes and objects

Class: A description of a class of things. It is an abstract, conceptual definition

Object: Is each individual of something of that class that actually exists, and thus is also called an instance.

The key point of object-oriented programming is the design of class, and the design class is the member of the design class.

The relationship between the two: objects are derived from class new.

3. Rules of object-oriented thought implementation

  1. Create a class and design its members

  2. Creates an object for the class

  3. By object. Property or object. Method calls the structure of the object

Addendum: usage instructions for several concepts

  • Attribute = member variable = field = field, field
  • Method = member method = function = method
  • Create class object = instantiation of class = instantiation of class

4. Object creation and object memory parsing

Typical code:

Person p1 = new Person();
Person p2 = new Person();
Person p3 = p1;// No new object is created, shared object entity in heap space.
* If multiple objects of a class are created, each object has its own set of class attributes. (non-static) * means that if we modify the property a of one object, the value of the property A of the other object is not affected. * /

Copy the code

Memory parsing:

5. JVM memory structure

After compiling the source program, one or more bytecode files are generated. The resulting bytecode files are interpreted and run using the loaders and interpreters of the classes in the JVM. This means that the class corresponding to the bytecode file needs to be loaded into memory, which involves memory parsing.

Vm stack: refers to the stack structure. We store local variables in a stack structure

Virtual heap: We load new structures (e.g. arrays, objects) into the pair space.

Added: The object’s properties (non-static) are loaded in the heap space.

Method area: load information of the class, constant pool, static field

6. Anonymous Objects

The object we create is not explicitly assigned to a variable name. That is, anonymous objects

Features: Anonymous objects can only be called once.

new Phone().sendEmail();
new Phone().playGame();
        
new Phone().price = 1999;
new Phone().showPrice();/ / 0.0

Copy the code

Application Scenarios:

PhoneMall mall = new PhoneMall();

// Use of anonymous objects
mall.show(newPhone()); Among them,class PhoneMall{
    public void show(Phone phone){ phone.sendEmail(); phone.playGame(); }}Copy the code

7. “Everything is an object”

In the Java language category, we all encapsulate functions and structures into classes, and invoke specific functional structures through instantiation of classes

  • Scanner, String, etc
  • File: a File
  • Web resource: URL

When it comes to the interaction between the Java language and the front-end HTML and the back-end database, the structure of the front and back end is reflected as classes and objects when interacting at the Java level.

One of the structures of a class: an attribute

1. Properties vs. local variables

1.1 Similarities:

  • Define variable format: data type variable name = variable value

  • Declare first, use later

  • Variables have their corresponding scopes

1.2 Differences:

1.2.1 Differences in declared locations in classes

  • Attributes: Defined directly within a pair of {} of the class
  • Local variables: Variables declared inside methods, method parameters, code blocks, constructor parameters, and constructors.

1.2.2 Differences on permission modifiers

  • Attributes: You can specify the permissions of attributes when declaring them, using permission modifiers.
  • Common permission modifiers: private, public, default, protected –> encapsulation
  • Currently, when declaring attributes, use the default.
  • Local variables: Permission modifiers cannot be used.

1.2.3 Default Initialization:

  • Attributes: Attributes of a class, depending on their type, are initialized by default.

  • Int (byte, short, int, long: 0)

  • Float (float, double: 0.0)

  • Char: 0 (or ‘\u0000’)

  • Boolean (Boolean: false)

  • Reference data type (class, array, interface: NULL)

  • Local variables: No default initialization values.

    • This means that we must explicitly assign a local variable before calling it.
    • Specifically: when the parameter is called, we assign it.

1.2.4 Loading Location in Memory:

  • Property: Loaded into heap space (non-static)
  • Local variables: loaded into the stack space

2. Classification of variables:

  • Method 1: Based on the data type:

  • Method 2: according to the declared position in the class:

The second structure of a class: methods

Definition: Describes what the class should do.

1. Method Examples:

1.1 JDK methods:

  • Math class: SQRT () random()…

  • Scanner class: 'nextXxx()'...Copy the code
  • The Arrays class: ` sort () ` ` binarySearch () ` ` toString () ` ` equals () `...Copy the code

1.2 Custom Methods:

 public void eat(a){
     System.out.printly("I want to eat!!");
 }

 public String getNation(String nation){
     System.out.printly("Current location is" + nation);
 }

Copy the code

1.3 Method declaration:

Permission modifier return value type Method name (parameter list){method body}Copy the code

Static, final, abstract, etc.

2. Method description:

2.1 Permission Modifiers:

There are four permission modifiers specified by Java: private, public, default, and protected

For more details, see the article “Three Features of Object Orientation”.

2.2 Return Value Type:

2.2.1 Return value vs No return value

  • If the method has a return valueYou must specify the type of the return value when the method is declared. In addition, the return keyword is used to return a variable or constant of the specified type:The return data.
  • If the method returns no valueVoid is used when the method is declared. In general, methods that do not return a value do not need to use a return. If used, only usedreturn;To end this method.

2.2.2 Should methods define return values?

1.

② Specific problems are analyzed

2.3 Method naming conventions

  • Belong to the identifier, follow the rules and specifications of the identifier, “know by name”
  • Method names should follow the small hump namingaaaBbbCcc
  • It is best to use English words for method names, not pinyin or abbreviations
  • For more specification requirements, see the Java Development Manual.

2.4 About parameter lists

Methods can declare zero, one, or more parameters.

You can also use deformable parameters, but deformable parameters must be left at the end, as described in Part 5 of this chapter.

Format: Data type 1 Parameter 1 Data type 2 Parameter 2…..

Should I define parameters when defining methods?

1.

② Specific problems are analyzed

2.5 the method body

Is the embodiment of the function of the method, through the loop branch, condition judgment and other statements to complete complex logical relations.

Other methods can be called from a method, directly from a class, or from an instantiation object of a class.

Note: You cannot define new methods in a method

3. Use of methods

  • Methods in a class can call properties or methods of the current class directly, or in different classes through the class’s instantiation object.
  • Special: method A calls itself again – recursive method. (Self call)

See Part 7 of this chapter for the use of recursive methods.

4. Method overloading

4.1 Concept of overloading

More than one method with the same name is allowed in the same class, as long as they have different parameters or parameter types.

“Two same but different “:

  • Same: same class, same method name
  • Different parameter lists: The number and type of parameters are different

4.2 Examples of overloading:

// Overloaded sort()/binarySearch() from the Arrays class; PrintStream the println ()
// Example 2:
// The following four methods constitute overloading
public void getSum(int i,int j){
    System.out.println("1");
}

public void getSum(double d1,double d2){
    System.out.println("2");
}

public void getSum(String s ,int i){
    System.out.println("3");
}

public void getSum(int i,String s){
    System.out.println("4");
}

Copy the code

Instances that do not constitute an overload:

// The following three methods cannot constitute an overload with the above four methods
public int getSum(int i,int j){
    return 0;
}
    
public void getSum(int m,int n){}private void getSum(int i,int j){}Copy the code

4.3 Judgment of overloaded methods

How to determine if method overloading constitutes?

Strictly by definition: two are the same and different. It doesn’t matter if a method has permission modifiers, return value types, parameter names, or method bodies!

How to determine a method call in a class:

Method name –> Parameter list

5. Variable number parameter method

5.1 Instructions

  • New in JDK 5.0

  • Before JDK 5.0: Use array parameters to define methods, passing in multiple variables of the same type

    Public static void test(int a, String[] books);

  • After JDK 5.0: use variable number parameters to define methods, passing in multiple variables of the same type

    Public static void test(int a, String... books);

Specific use:

  • Format of variable parameter: data type… The variable name

  • When calling a method with a variable number of parameters, the number of arguments passed can be: 0, 1,2,…..

  • Methods with variable number parameters have the same name as the Chinese method of this class. Methods with different parameters form overloads

  • An overload does not occur between arrays that have methods with the same names and parameters of the same type. In other words, the two cannot coexist.

  • Variable-number parameters must be declared at the end of method parameters.

  • Variable parameter *** in the parameter of the method, can declare at most one variable parameter ***.

5.2 Examples

public void show(int i){}public void show(String s){
    System.out.println("show(String)");
}

public void show(String ... strs){
    System.out.println("show(String ... strs)");

    for(int i = 0; i < strs.length; i++){ System.out.println(strs[i]); }}// Cannot coexist with the previous method
// public void show(String[] strs){
//      
/ /}
// When called: morphable participation array similar
test.show("hello");
test.show("hello"."world");
test.show();

test.show(new String[]{"AA"."BB"."CC"});

Copy the code

6. Java’s value passing mechanism

6.1 Assignment examples for variables in the method:

System.out.println("*********** Basic data type: ****************");
int m = 10;
int n = m;

System.out.println("m = " + m + ", n = " + n);

n = 20;

System.out.println("m = " + m + ", n = " + n);

System.out.println("*********** Quoted data type: ****************");

Order o1 = new Order();
o1.orderId = 1001;

Order o2 = o1;// O1 and o2 are assigned the same address and refer to the same object entity in the heap space.

System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " +o2.orderId);

o2.orderId = 1002;

System.out.println("o1.orderId = " + o1.orderId + ",o2.orderId = " +o2.orderId);

Copy the code

Rule: If the variable is a primitive data type, the value assigned is the value of the data the variable holds. If the variable is a reference data type, the value assigned is the address value of the data the variable holds.

6.2 Parameter concepts for methods

Parameter: the argument declared in parentheses when a method is defined: the data actually passed to the parameter when a method is called

6.3 Parameter Passing Mechanism in Java: Value passing mechanism

Rules:

  • If the parameter isBasic data types, where the argument is assigned to the parameter the actual value of the data stored by the argument.
  • If the parameter isReference data type, which assigns the parameter the address of the data stored in the argument.

Promotion:

  • If the variable is a primitive data type, the value assigned is the data value that the variable holds.
  • If the variable is a reference data type, the value assigned is the address value of the data the variable holds.

6.4 Memory Parsing:

Memory parsing method points:

1. Memory structure: stack (local variables), heap (new structures: objects (non-static member variables), array 2. Variables: Member variables vs local variables (inside method, method parameters, constructor, constructor parameters, code block)

For example, a

For example, two

7. Recursive methods

Recursive methods: a method body calls itself.

Method recursion consists of an implicit loop that executes a piece of code repeatedly, but this repetition does not require loop control. A recursion must recurse in a given direction, otherwise it becomes an infinite recursion, similar to an infinite loop.

Examples of recursive methods:

// Example 1: Calculate the sum of all natural numbers between 1 and n
public int getSum(int n) {/ / 3

    if (n == 1) {
        return 1;
    } else {
        return n + getSum(n - 1); }}// Example 2: Compute the product of all natural numbers between 1 and n :n!
public int getSum1(int n) {

    if (n == 1) {
        return 1;
    } else {
        return n * getSum1(n - 1); }}/ / example 3: a known sequence: f (0) = 1, f (1) = 4, f (n + 2) = 2 * f (n + 1) + f (n),
// where n is an integer greater than 0, find f(10).
public int f(int n){
    if(n == 0) {return 1;
    }else if(n == 1) {return 4;
    }else{
        // return f(n + 2) - 2 * f(n + 1);
        return 2*f(n - 1) + f(n - 2); }}// Example 4: Fibonacci sequence

// Example 5: Hannotta problem

// Example 6: Fast queue

Copy the code

8. Method rewrite

8.1 What is method overwriting (override or Overwrite)?

When a subclass inherits from its parent class, it can override methods with the same name and parameters in the parent class.

8.2 Application of rewriting:

When a subclass object is created and a method with the same name and argument is called from the subclass object, the subclass overrides the method.

8.3 Rewriting Examples:

/ / parent class
class Circle{
public double findArea(a){}/ / area
}
/ / subclass
class Cylinder extends Circle{
public double findArea(a){}// Find the surface area} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ / parent class
class Account{
public boolean withdraw(double amt){}}/ / subclass
class CheckAccount extends Account{
public boolean withdraw(double amt){}}Copy the code

8.4 Rules rewritten:

Method declaration:

Permission modifier Return value type Method name (parameter list)throwsType of exception {/ / the method body
}

Copy the code

Conventions are commonly known as overridden methods in subclasses and overridden methods in superclasses

  1. The method names and parameter lists of methods overridden by subclasses are the same as those of methods overridden by their parent class
  2. The permission modifier of a method overridden by a subclass is no less than that of a method overridden by its parent class

Special case: A subclass cannot override a method declared private by its parent class

  1. Return value type:
  • If the parent overrides a method whose return type is void, the child overrides a method whose return type must be void
  • The return value type of the method overridden by the parent class is type A, then the return value type of the method overridden by the subclass can be class A or A subclass of class A
  • If the method overridden by its parent class returns a primitive data type (e.g., double), the method overridden by its subclass must return the same primitive data type (also double).
  1. A method overridden by a subclass may throw no more than the method overridden by its parent class.

Methods with the same name and arguments in subclasses and superclasses are either declared non-static (consider overrides) or static (not overrides).

Child and parent classes are generally kept consistent in development

8.5 Interview Questions:

Distinguish between method overrides and overloads?

  1. Concepts of the two:
  • Method rewriting: after a subclass inherits its parent class, it can override methods with the same name and parameters in the parent class.
  • Method overloading: More than one method with the same name is allowed in the same class, as long as they have different arguments or parameter types.
  1. The specific rules for overloading and overwriting: Overloading: two same different, overwriting
  2. Overloading: does not show polymorphism. Rewrite: manifests as polymorphism.
  3. From a compile and run perspective:
  • Overloading means that multiple methods with the same name are allowed to exist with different parameters. The compiler modifies the name of a method with the same name based on its argument list. To the compiler, these methods with the same name become different methods. Their call addresses are bound at compile time. Java overloading can include superclasses and subclasses, that is, subclasses can override methods with the same name and different parameters of the parent class.
  • So in the case of overloading, the compiler determines the method to be called before the method is called, which is called “early binding” or “static binding”;
  • With polymorphism, the explain runner does not determine the specific method to call until the moment the method is called, which is called “late binding” or “dynamic binding.”

To quote Bruce Eckel: “Don’t be silly, if it’s not late bound, it’s not polymorphic.”

Class structure 3: constructor

(1) Constructor

What constructors do :(you need constructors whenever you build objects)

  1. Create an object

  2. Initializes information about an object

2. Instructions:

  • If the class constructor is not explicitly defined, the system provides a constructor for empty parameters by default
  • Define the format of the constructor:Permission modifier class name (parameter list){}
  • Defined in a classMultiple constructorsEach constitutes a heavy load
  • Once we have explicitly defined the constructor for the class, the system no longer provides the default empty parameter constructor
  • In a class,There will be at least one constructor.

3. Constructor examples:

// Constructor is not equal to method
public Person(a){
    System.out.println("Person().....");
}

public Person(String n){
    name = n;

}

public Person(String n,int a){
    name = n;
    age = a;
}

Copy the code

The default constructor permissions are the same as the class permissions

4. Order of attribute assignment

Summary: The order in which attributes are assigned

1 Default initialization

② Explicit initialization

Class in the constructor

④ Pass “object. Method “or” object. Property “, assign value

The sequence of the above operations is ① – ② – ③ – ④

5. JavaBean concepts

A JavaBean is a Java class that meets the following standards:

  • Classes are public
  • aNo argumentsA public constructor for
  • Property and corresponding get and set methods

Class structure 4: code block

Code blocks (initialization blocks) (less important than properties, methods, constructors)

1. Function of code block:

Information used to initialize a class or object

2. The classification:

Code blocks that use modifiers can only be classified static: static code blocks vs non-static code blocks

3. Static vs. non-static code blocks

Static code block:

  • Statements can be output internally
  • It is executed as the class is loaded and only once
  • Function: Initializes information about a class
  • If multiple static code blocks are defined in a class, they are executed in the order in which they are declared
  • Execution of static code blocks takes precedence over execution of non-static code blocks
  • Static code blocks can only call static properties and methods, not non-static structures

Non-static code blocks:

  • Statements can be output internally
  • Executes as the object is created
  • Each time an object is created, a block of non-static code is executed
  • Function: Initializes the properties of an object when it is created
  • If multiple non-static code blocks are defined in a class, they are executed in the order they are declared
  • Non-static code blocks can call static properties, static methods, or non-static properties, non-static methods

Note: when instantiating a subclass object, it involves the loading order of static code block, non-static code block and constructor in the parent class and subclass: parent and child, static first.

For example, a

class Root{
    static{
        System.out.println("Static initialization block for Root");
    }
    {
        System.out.println("Common initialization block for Root");
    }
    public Root(a){
        System.out.println("No-argument constructor for Root"); }}class Mid extends Root{
    static{
        System.out.println("Static initializer block for Mid");
    }
    {
        System.out.println("Common initialization block for Mid");
    }
    public Mid(a){
        System.out.println("Parameterless constructor for Mid");
    }
    public Mid(String msg){
        Call an overloaded constructor in the same class through this
        this(a); System.out.println("Mid with parameter constructor, whose parameter value:"+ msg); }}class Leaf extends Mid{
    static{
        System.out.println("Static initializer block for Leaf.");
    }
    {
        System.out.println("Common initializer block for Leaf.");
    }   
    public Leaf(a){
        // Call the constructor with a string argument in its parent class through super
        super("Call the parent constructor");
        System.out.println("The Leaf constructor."); }}public class LeafTest{
    public static void main(String[] args){
        new Leaf(); 
        //new Leaf();}}Copy the code

For example, two

class Father {
    static {
        System.out.println("11111111111");
    }
    {
        System.out.println("22222222222");
    }

    public Father(a) {
        System.out.println("33333333333"); }}public class Son extends Father {
    static {
        System.out.println("44444444444");
    }
    {
        System.out.println("55555555555");
    }
    public Son(a) {
        System.out.println("66666666666");
    }

    public static void main(String[] args) { // The parent and child are static first
        System.out.println("77777777777");
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * *");
        new Son();
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * *");

        new Son();
        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * *");
        newFather(); }}Copy the code

4. Assignment order of attributes

1 Default initialization

② Explicitly initialize /⑤ Assign values in code blocks

Class in the constructor

④ After you have the object, you can pass the object. Property “or” object. Method “to perform the assignment

The execution sequence is ① – ② / ⑤ – ③ – ④

Class structure 5: inner class

Inner class: The fifth member of a class

1. Inner class definition:

Java allows one class A to be declared in another class B, so class A is the inner class and class B is the outer class.

2. Classification of inner classes:

Member inner classes (static, non-static) Local inner classes (inside methods, inside code blocks, inside constructors)

3. Understanding of member inner class:

On the one hand, as a member of an external class:

  • Invoke the structure of the external class
  • Can be modified by static
  • It can be decorated with four different permissions

On the other hand, as a class:

  • Properties, methods, constructors, and so on can be defined within a class

  • Can be final to indicate that this class cannot be inherited. The implication is that without using final, it can be inherited

  • Can be modified by abstract

4. Member inner class:

4.1 How do I create an object of a member inner class? (static, non-static)

// Create an instance of a static Dog inner class (static member inner class):
Person.Dog dog = new Person.Dog();

// Create an instance of a non-static Bird inner class (non-static member inner class):
// Person.Bird bird = new Person.Bird(); / / error
Person p = new Person();
Person.Bird bird = p.new Bird(a);

Copy the code

4.2 How do I call the structure of an external class from a member inner class?

class Person{
    String name = "Xiao Ming";
    public void eat(a){}// Non-static member inner class
    class Bird{
        String name = "Cuckoo";
        public void display(String name){
            System.out.println(name);// Parameter to the method
            System.out.println(this.name);// Inner class attributes
            System.out.println(Person.this.name);// Attributes of the external class
            //Person.this.eat();}}}Copy the code

5. Use of local inner classes:

// Return an object of a class that implements the Comparable interface
public Comparable getComparable(a){

    Create a class that implements the Comparable interface: a local inner class
    // Method 1:
    // class MyComparable implements Comparable{
    //
    // @Override
    // public int compareTo(Object o) {
    // return 0;
    / /}
    //          
    / /}
    //      
    // return new MyComparable();

    // Method 2:
    return new Comparable(){

        @Override
        public int compareTo(Object o) {
            return 0; }}; }Copy the code

Note:

In a local inner class method (e.g. : show), a local variable (e.g. : num) declared ina local inner class method (e.g. : method) is required to be final.

Cause: Local inner classes also generate bytecode files. When calling local variables of the owning class, because there are two classes, the attributes of the owning class cannot be modified. Therefore, the owning class with its property set to final provides a copy of the inner class invocation, while the inner class cannot be modified.

  • JDK 7 and earlier: Requires that this local variable be explicitly declared final
  • JDK 8 and later: You can omit final declarations

Summary: Member inner classes and local inner classes, when compiled, generate bytecode files. Format: Member inner class: outer class $Inner class name. class local inner class: outer class $numeric inner class name. class