Java Chapter 5 object oriented programming (middle)

Object oriented inheritance II

1, Inherited benefits

1. Reduce the complexity of the code and improve the reusability of the code
2. Convenient for function expansion
3. It provides a premise for the use of polymorphism

2, Inherited format

class A extends B{ }
A: Subclass, derived class, subclass
B: Parent class, superclass, base class, superclass

Embodiment: once subclass A inherits parent class B, subclass A obtains all the structures declared in parent class B: attributes and methods
In particular, for the private properties and methods declared in the parent class, after the child class inherits the parent class, it is still considered to have obtained the private structure of the parent class.
After the subclass inherits the parent class, it can also declare its own unique properties and methods: to realize the expansion of functions

3, Rules on inheritance in Java

1. A class can be inherited by multiple subclasses
2. A class can only have one parent class: single inheritance of classes in Java
3. Child parent class is a relative concept
4. The parent class directly inherited by the child class is called direct parent class. The parent class of indirect inheritance is called indirect parent class
5. After the subclass inherits the parent class, it obtains the properties and methods declared in the direct parent class and all indirect parent classes

4, Object class

1. If we do not explicitly declare the parent class of a class, this class inherits from Java Lang.Object class
2. All Java classes (except java.lang.object class) inherit from java.lang.object class directly or indirectly
3. All Java classes have Java Functions declared by lang.Object class

5, Override of method (override/overwrite)

1. Definition: methods inherited from the parent class can be modified as needed in subclasses, also known as method reset and overwrite. When the program is executed, the methods of the child class override the methods of the parent class.
2. Requirements:
① The method overridden by the subclass must have the same method name and parameter list as the method overridden by the parent class
② The return value type of the method overridden by the subclass cannot be greater than the return value type of the method overridden by the parent class
③ The access permission of the method overridden by the subclass cannot be less than that of the method overridden by the parent class; A subclass cannot override a method declared as private permission in a parent class
④ The exception thrown by a subclass method cannot be greater than the exception of the overridden method of the parent class
3. Note: the methods with the same name and parameters in the subclass and the parent class must be declared non static (that is, overridden) or static (not overridden) at the same time. Because the static method belongs to the class, the subclass cannot override the methods of the parent class.

Interview question: overloading and rewriting of distinguishing methods

4. Regulations:

Method declaration: permission modifier return value type method name (formal parameter list) throws Type of exception
{
	//Method body
}
The Convention is commonly known as: the method in the subclass is called overridden, and the method in the parent class is called overridden
 Return value type:
The return value type of the method whose parent class is overridden is void,The return value of the method overridden by the subclass can only be void
 The method type whose parent class is overridden is A Type, the return value of the method overridden by the subclass is A Class or A Subclass of
 The return value type of the method whose parent class is overridden is the basic data type( eg.double),The return value of the method overridden by the subclass
 Must be the same basic data type

6, Use of super keyword

1.super is understood as the parent class
2.super can be used to call: properties, methods and constructors
3. Use of super:
3.1 we can explicitly call the properties and methods declared in the parent class by using "super. Attribute" or "super. Method" in the method or constructor of the subclass. However, in general, it is customary to omit "super."
3.2 special case: when the properties of the same name are defined in the child class and the parent class, if we want to call the properties declared in the parent class in the subclass, we must explicitly use the "super. attribute" method to indicate that the attributes declared in the parent class are called.
3.3 special case: when a child rewrites the method in the parent class, if it wants to call the rewritten method in the parent class in the subclass method, it must explicitly use the "super. method" to indicate that the method is rewritten in the parent class.

4.super call constructor
4.1 we can explicitly call "super (formal parameter list)" in the constructor of the subclass to call the specified constructor declared in the parent class
4.2 the use of "super (formal parameter list)" must be in the first line of the subclass constructor
4.3 in the class constructor, we can only choose one from "this" or "super"
4.4 if there is no explicit declaration of "this" or "super" in the first line of the constructor, the constructor of the null parameter of the parent class is called by default
4.5 among multiple constructors of a class, "super (formal parameter list)" is used in the constructor of at least one class to call the constructor in the parent class

7, The whole process of subclass object instantiation

1. From the results:
(inheritance) the subclass inherits the properties and methods declared in the parent class obtained after the parent class. If the subclass object is created, the properties declared in all the parent classes will be loaded in heap space
2. In terms of process:
When we create a subclass object through the subclass constructor, we will call the constructor of its parent class directly or indirectly, and then call the constructor of the parent class of the parent class until Java. Net is called Up to the null parameter constructor in the lang.Object class. Because all the parent class structures have been loaded, you can see that there are structures in the parent class in memory, and the child class object can consider calling.
Explicit: Although the constructor of the parent class is called when creating a subclass object, an object has been created from beginning to end, that is, a subclass object of new


8, Object oriented feature 3: polymorphism

1. Understanding: multiple forms of a thing
2. The reference of the parent class points to the object of the child class (or the reference assigned to the parent class by the object of the child class)
3. Use: (virtual method call) when calling a method with the same name and parameter as the child parent class, during compilation, only the methods declared in the parent class can be called, and the actual implementation is that the child class overrides the method of the parent class

4. Usage premise: ① inheritance relationship of class ② rewriting of method

person p1 = new Student();
person p2 = new Man();
Person p3 = new Woman();
The reference of the parent class points to the object of the child class
 Example 1
package com.package1;

public class AnimalTest
{
    public void func1(Animal animal)
    {
        animal.eat();
        animal.shout();
    }
    public static void main(String[] args)
    {
        AnimalTest T1 = new AnimalTest();
        T1.func1(new Dog());
        T1.func1(new Cat());
    }
}

public class Cat extends Animal
{
    public void eat()
    {
        System.out.println("Cat eat: fish");
    }
    public void shout()
    {
        System.out.println("Cat: meow meow meow");
    }
}

public class Dog extends Animal
{
    public void eat()
    {
        System.out.println("Dogs eat: bones");
    }
    public void shout()
    {
        System.out.println("Dog barking: woof, woof, woof");
    }
}
public class Animal
{
    public void shout()
    {
        System.out.println("Animal: howling");
    }
    public void eat()
    {
        System.out.println("Animals: eat");
    }
}
Example 2:
class Order
{
	public void method(Object obj)//A formal parameter can be any object
	{
	
	}
}
Example 3: operating the database
class Driver
{
	public void doData(Connection conn)//conn = new MySQLConnection();
	// conn = new OracleConnection();
	{
		conn.method1();
		conn.method2();
		conn.method3();
	}
}

5. Object polymorphism: only applicable to methods, not attributes (see the left for compilation and operation)

9, Use of downward transformation

After the polymorphism of the object, the properties and methods specific to the subclass are actually loaded in the memory. However, because the variable is declared as the parent type, only the properties and methods of the parent class can be called during compilation, and the properties and methods specific to the subclass cannot be called.

Q: How can I call subclass specific methods?
A: Use a cast, that is, a downward transformation

Example
Person p2 = new Man();
Man m1 = (Man)p2;
m1.earnMoney();
m1.isSmoking = true;
When strong rotation is used, it may occur ClassCastException So it needs to be used instanceof keyword
Woman w1 = (Woman)p2;
w1.goshopping();

10, Use of instanceof keyword

a instanceof A: judge whether object a is an instance of class A. If yes, return true; if not, return false

Example
if(p2 instanceof Woman)
{
	Woman w1 = (Woman)p2;
	w1.goshopping();
}

If a instanceof A returns true, a instanceof B also returns true Where class B is the parent of class A

11, Use of Object class

1.Object class is the root parent class of all Java classes
2. If the extension keyword is not used in the class declaration to indicate its parent class, the default parent class is Java Lang.Object class
3. Functions (properties and methods) in object class
Properties: None
Methods: equals() / toString() / getclass() / hashCode() / clone() / finalize() / wait() / notify()
/notifyall()
4. The object class declares only one null parameter constructor

public class person
{
...
}
Equivalent to:
public class person extends Object
{
...
}

12, Use of the equals() method

1. Review the use of = =
Can be used in basic data type and reference data type variables
If you are comparing variables of basic data type: compare whether the data saved by the two variables are equal (not necessarily of the same type)
If you are comparing reference data type variables, compare whether the address values of the two objects are the same, that is, whether the two references point to the same entity
2. The equals () method is a method, not an operator, and can only be applied to reference data types
3. The equals() and = = defined in the object class are the same
4. String, Date, File, wrapper class, etc. override the equals() method in the Object class. After rewriting, the comparison is whether the "entity content" of the two objects is the same
5. Generally, if equals() is used for a custom class, it is also used to compare whether the "entity content" of the two objects is the same. Then, we need to override equals() in the Object class

Rewriting principles and framework examples

@Override 
    public boolean equals(Object obj)
    {
        if(obj == this) return true;
        if(obj instanceof person)
        {
            person p = (person)obj;
            return this.isMale == p.isMale&&this.age == p.age && this.name.equals(p.name);
        }//Note that the comparison of strings is equal
        return false;
    }

13, toString() method

1. When we output the reference of an object, we actually call the toString() of the current object
2. Definition of toString() in object class:

	public String toString()
	{
		return getClass().getName() + "@" + Integer.toHexString(hashCode());
	}
	public class ToStringTest
	{
		Customer cust1 = new Customer("Tom",21);
		System.out.println(cust1.toString());//com.exer1.java.Customer@15db9743
		System.out.println(cust1);//com.exer1.java.Customer@15db9743
		String str = new String("A1");
		system.out.println(str);//A1
		String Medium println Method has override
		Date date = new Date(1234567890L);
        System.out.println(date.toString());//Thu Jan 15 14:56:07 CST 1970
        Date Medium println Method has override
	}

3. String, Date, File, wrapper class, etc. override the toString() method in the Object class, so that the "entity content" information is returned when the toString() of the Object is called
4. The custom class can also override the toString() method. When this method is called, the "entity content" of the object will be returned

@Override
public class Customer
{
	private String firstName;
    private String lastName;
    private Account account;
    @Override
    public String toString()
    {
        return new String(this.lastName+" "+this.firstName);
    }

    public static void main(String[] args)
    {
        System.out.println(new Customer("Bo","king").toString());
    }
}

14, JUnit unit test in Java

Steps:
1. Select the current project - right click to select: build path - add libraries - JUnit 4 - next
2. Create a Java class for unit testing. At this time, the Java class requirements are: public, provide a public and parameterless constructor
3. Declare the unit test method in this class: the method permission is public, the return value is void, and there are no formal parameters
4. The annotation @ test needs to be declared on this unit test method and imported into the unit test class: import org junit. Test;
5. After declaring the unit test method, you can test the relevant code in the method body
6. Double click the unit test method name and right click to run
Note: there is no exception in the execution result: green bar, exception: red bar

15, Use of Wrapper


1.Java provides wrapper classes corresponding to 8 basic data types, so that the variables of basic data types have the characteristics of classes
2. Three types of conversion

Basic data type - > wrapper class: call the constructor of the wrapper class

		int num = 20;
        Integer Num = new Integer(num);
        System.out.println(Num.toString());
        System.out.println(new Integer("123"));
        System.out.println(new Float(12.3f));
        System.out.println(new Double(3.14));

Wrapper class - > basic data type: call xxxValve() of wrapper class

        Integer integer = new Integer(10);
        System.out.println(integer.intValue() + 50);
        Float F = new Float(13.5f);
        System.out.println(F.floatValue());

JDK5.0 new features: automatic packing and automatic unpacking

        Integer integer = 10;
        Boolean B1 = true;
        //Auto packing: basic data type -- > Packing class
        System.out.println(integer.toString());
        int num = integer;//Automatic unpacking: packaging class -- > basic data type

Basic data type, wrapper class - > String type: call valueof (xxx) overloaded by String

        int num1 = 10;
        //Method 1: join operation
        String str1 = num1 + "";
        System.out.println(str1);
        //Method 2: call valueof (xxx) of String
        float f1 = 12.4f;
        String str2 = String.valueOf(f1);
        Double d1 = 12.4;
        String str3 = String.valueOf(d1);
        System.out.println(str2);
        System.out.println(str3);

String type - > basic data type, wrapper class: call parsexxx() of wrapper class

        String int1 = "123";
        int num1 = Integer.parseInt(int1);
        System.out.println(num1 + 1);
        String bool1 = "true";
        boolean b1 = Boolean.parseBoolean(bool1);
        System.out.println(b1);
        bool1 = "true1";
        b1 = Boolean.parseBoolean(bool1);
        System.out.println(b1);

o1 is 1.0. Reason: since the type must be unified, the type is improved after packing, and the box shall be unpacked during output
o2 is 1

[interview questions]

        Integer i = new Integer(1);
        Integer j = new Integer(1);
        System.out.println(i==j);//false, the address value is compared

        Integer m = 1;
        Integer n = 1;
        System.out.println(m==n);//true, unpack after automatic packing

        Integer x = 128;
        Integer y = 128;
        System.out.println(x==y);//false, look at the source code: Integer [] is defined in IntegerCache,
        //The integer in the range of - 128-127 is saved. If automatic packing is used, the number in this range is directly from the array
        //To improve efficiency, Integer objects need to be created for numbers outside this range

Keywords: Java intellij-idea

Added by killah on Fri, 24 Dec 2021 11:50:51 +0200