Inheritance and polymorphism
▲ class, superclass and subclass ▲ abstract class
▲ Object: super class interface of all classes
▲ object wrapper and automatic packing
1. Class, superclass and subclass
Inheritance: the subclass inherits all the attributes and methods of the parent class and extends them as required. The keyword extends indicates inheritance.
Parent class: existing class
Subclass: a class derived from the parent class, which inherits the "is a" relationship with the parent class.
- Generic methods are placed in superclasses and special-purpose methods are placed in subclasses
- You can add fields, methods or methods that override superclasses in subclasses. You must not delete any inherited fields and methods
- Single root inheritance principle: each class can only inherit one class and can implement multiple interfaces
public class Manager extends Employee { Add method and domain }
Classes used in this chapter:
public class Employee //Parent class { private String name; private double salary; private LocalDate hireDay; public Employee(String name, double salary, int year, int month, int day) { this.name = name; this.salary = salary; hireDay = LocalDate,of(year, month, day); } public String getName() { return name; } public double getSalary() { return salary; } public LocalDate getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; } } public class Manager extends Employee //Subclass { private double bonus; public Manager(String name, double salary, int year, int month, int day) //Subclass constructor { super(nanie, salary, year, month, day); bonus = 0; } public double getSalary()//Overwrite { double baseSalary = super.getSalary(); //Calling the parent class private domain member data return baseSalary + bonus; } public void setBonus(double b)//Method of adding{ bonus = b; } }
2. override method
: the subclass has the same method as the parent class (the name and formal parameters are the same)
- The return type is not part of the signature. It can be different, but the compatibility of the return type should be guaranteed
- Subclass methods cannot be less visible than superclass methods. If the parent class method is public, the child class method must be declared public
- Although a subclass inherits the members of the parent class, it cannot directly access the private domain of the parent class. It needs to call the parent class interface
public double getSalary() { return salary + bonus; // won't work } public double getSalary() { double baseSalary = getSalaryO;// still won't work return baseSalary + bonus; } public double getSalary()//√ { double baseSalary = super.getSalary(); return baseSalary + bonus; }
3. Subclass constructor:
First construct the super class, and then initialize the subclass members.
- The statement of super calling constructor must be the first statement of subclass constructor. If not, it will be added by default
public Manager(String name, double salary, int year, int month, int day) { super(name, salary, year, month, day); bonus = 0; }
Function of super keyword:
- Call the method of the parent class.
- Call the constructor of the superclass.
4. Polymorphism
The phenomenon that a class object variable can indicate multiple actual classes is called polymorphism
The role of polymorphism: to control the dynamic behavior of different objects in a class with a unified interface
- Generally, parent variables can indicate subclass objects, but subclass variables cannot indicate parent objects unless downward type conversion is performed
- Generally used with overrides
4.1 dynamic binding
: the virtual machine knows the actual referenced object type and can automatically select which method to call at run time.
Employee[] staff = new Employee[3]; staff[0] = boss; //polymorphic staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1 ); staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); for (Employee e : staff) System.out.println(e.getName() + " " + e.getSalary());//The virtual machine knows whether to call Manager or Employee's getSalary() //But the compiler treats staff[0] as an Employee object boss.setBonus(5000); // OK staff[0].setBonus(5000); // Error
4.2 cast type
Up conversion: conversion from child class to parent class (direct conversion)
Downward conversion: conversion from parent class to child class (instanceof)
- Type conversion can only occur within the inheritance hierarchy
- You should use instanceof to check before converting a parent class to a child class
Manager boss = (Manager)staff[0]; //Up if (staff[1] instanceof Manager)//Down{ boss = (Manager) staff[1]; }
5. Abstract class
: classes that cannot be materialized can improve member variables and methods that are not implemented.
Abstract keyword: defines abstract classes and abstract methods.
- Subclasses can inherit from abstract classes, but they must implement all of the parent classes
abstract method. If it cannot be fully implemented, the subclass must also be defined
Is an abstract class.
Composition of abstract classes:
- (optional) unlimited number of member variables
- (optional) specific methods. The number of methods is unlimited
- (optional) abstract methods, with the abstract keyword, unlimited number
- Abstract classes can contain concrete data and concrete methods, but it's best not to
- Interfaces must be abstract methods, even without abstract
public abstract class Person { String s; public abstract String getDescription(); }
6. Interface
: it is a requirement description, which contains abstract methods, and the interface is not an interface
public interface Comparable //Interface definition { int compareTo(Object other); } public int compareTo(Object other Object) //Interface implementation { Employee other = (Employee) otherObject; return Double.compare(salary, other.salary); }
6.1 interface domain and method:
- All methods in the interface automatically belong to public abstract. Therefore, it is not necessary to provide the keyword public abstract when declaring a method in an interface
- When implementing the interface, you must declare the method as public and implement all abstract methods. If not, it can only become an abstract class.
- An interface must not contain an instance domain. An interface can be regarded as an abstract class without an instance domain, but there are some differences between the two concepts
- An interface cannot contain instance fields or static methods, but it can contain constants. The fields in the interface will be automatically set to the constant public static final.
6.2 characteristics of interface:
- Interfaces can also be extended.
public interface Moveable { void move(double x, double y); } public interface Powered extends Moveable { double milesPerCallon(); }
- Each class can only have one superclass, but it can implement multiple interfaces. Use commas to separate the implemented interfaces.
class Employee implements Cloneable, Comparable
- In Java SE 8, static methods are allowed to be added to the interface. In theory, there is no reason to think that this is illegal. However, this is contrary to the original intention of taking the interface as an abstract specification.
6.3 default method of interface
: you can provide a default implementation for interface methods, marked with the default modifier. (call or overwrite directly)
- You can declare all methods as default methods that do nothing. Just override the required method
public interface MouseListener { default void mousedieked(MouseEvent event) {} default void mousePressed(MouseEvent event) {} default void mouseReleased(MouseEvent event) {} default void mouseEntered(MouseEvent event) {} default void mouseExited(MouseEvent event) {} }
Default method conflict principle:
- Superclass takes precedence. If a superclass provides a concrete method, the default method with the same name and the same parameter type will be ignored
- Interface conflict. If a super interface provides a default method and another interface provides a method with the same name and the same parameter type (whether it is the default parameter or not), this method must be overridden to resolve the conflict
6.4 interface examples
public interface ActionListener //Listening events { void actionPerfonned(ActionEvent event); } class TimePrinter implements ActionListener //Interface implementation { public void actionPerformed(ActionEvent event) { System.out.println("At the tone, the time is " + new Date()); Toolkit.getDefaultToolkit().beep(); } } ActionListener listener = new TimePrinter(); //Like a parent variable, it accepts subtypes Timer t = new Timer(10000, listener); t.start()
7. Object: superclass of all classes
: the Object class is the ancestor of all classes in Java. In Java, each class is extended from it to build a type inheritance tree
- In Java, only basic types are not objects. For example, values of numeric, character, and Boolean types are not objects.
- The Object class has clone, equals, finalize and getClass by default,
hashCode, toString and other methods - Single root inheritance principle: each class can only inherit one class and can implement multiple interfaces
7.1 equals() method
: detect whether one object is equal to another object.
- Verify that references are equal
- Is it the same type
- Are the content fields equal
public class Employee{ public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) return true;//Inspection reference // must return false if the explicit parameter is null if (otherObject == null) return false; // if the classes don't match, they can't be equal if (getClassO != otherObject.getClass()) return false;//Check whether it is similar // now we know otherObject is a non-null Employee Employee other = (Employee) otherObject; // test whether the fields have identical values return name.equals(other.name) && salary = other.salary && hi reDay.equals(other.hireDay);//Inspection content field } }
getClass() will return the class to which an object belongs
Equals method of subclass: first call equals of superclass. If the detection fails, the objects cannot be equal. If the fields in the parent class are equal, you need to compare the instance fields in the child class.
public class Manager extends Employee{ public boolean equals(Object otherObject) { if (!super.equals(otherObject)) return false; // super.equals checked that this and otherObject belong to the same class Manager other = (Manager) otherObject; return bonus == other.bonus; } }
The equals method has the following characteristics:
- Reflexivity: X. equals (x) should return true for any non null reference X
- Symmetry: for any reference X and y, if and only if y.equals(x) returns true, x.equals(y) should also return true
- Transitivity: for any reference x, y, and Z, if x.equals(y) returns true, y.equals(z) returns true, and x.equals (z) should also return true
- Consistency: if the objects referenced by x and y do not change, repeated calls to x.equals(y) should return the same result.
- If the subclass can have its own concept of equality, the symmetry requirement will force getClass () to be used for detection
- If the concept of equality is determined by the superclass, you can use imtanceof() for detection
7.2 hashCode() method
: hash code is an integer value derived from the object. If x and Y objects are the same, x.hashcode() = = y.hashcode()
public class Employee { public int hashCode() { return 7 * name.hashCode() + 11* new Double(salary).hashCode0 + 13 * hireDay.hashCode(); } }
- The definitions of Equals and hashCode must be consistent: if x.equals(y) returns true, x.hashCode() must have the same value as y.hashCode().
- Hashcodes are equal, and equals is not necessarily equal
7.3 toString() method
: it is used to return a string representing the value of an object or the information it needs
public String toString() { return getClass().getName() + "[name=" + name +",salary: " + salary + ",hireDay=" + hireDay + "]"; }
8. Object wrapper and automatic packing
Wrapper: to convert a basic type such as int to an object
: Integer, Long, Float, Double, Short, Byte, Character, Void, Boolean
ArrayList<Integer> list = new ArrayList<>(); list.add(3);//Will be automatically converted to list add(Integer.value0f(3)); //This transformation is called autoboxing.
public class BoxClassTest { public static void main(String[] args) { int i1 = 10; Integer i2 = 10; // Automatic packing System.out.println(i1 == i2); //true // The basic type of automatic unpacking is compared with the packaging type, and the packaging type is automatically unpacked Integer i3 = new Integer(10); System.out.println(i1 == i3); //true // The basic type of automatic unpacking is compared with the packaging type, and the packaging type is automatically unpacked System.out.println(i2 == i3); //false // Compare two objects and compare their addresses. // i2 is a constant, which is placed in the constant pool of stack memory, and i3 is a new object, which is placed in heap memory Integer i4 = new Integer(5); Integer i5 = new Integer(5); System.out.println(i1 == (i4+i5)); //true System.out.println(i2 == (i4+i5)); //true System.out.println(i3 == (i4+i5)); //true // i4+i5 operation will automatically unpack I4 and i5 into basic type and obtain 10 // Comparing the basic type 10 with the object will enable the object to be unpacked automatically for basic type comparison Integer i6 = i4 + i5; // +The operation makes I4 and i5 unpack automatically to get 10, so i6 == i2 System.out.println(i1 == i6); //true System.out.println(i2 == i6); //true System.out.println(i3 == i6); //false } }