catalogue
5.1 class, superclass and subclass
5.1.6 prevent inheritance: final classes and methods
5.2 Object: superclass of all classes
5.2.3 equality test and inheritance (difficult)
5.3.2 accessing array list elements
5.3.3 compatibility of typing with the original array list
5.4 object wrapper and automatic packing
5.5 method of variable number of parameters
5.7.2 introduction to declaring exceptions
5.1 class, superclass and subclass
5.1.1 defining subclasses
Use the keyword extends to represent inheritance
In Java, all inheritance is public, but there is no private inheritance and protected inheritance in C + +
The keyword extends indicates that the new class being constructed derives from an existing class, which is called super class, base class or parent class; The new class is called subclass, paisu class or child class
When defining subclasses by extending superclasses, you only need to point out the differences between subclasses and superclasses
public class Manager extends Employee{ priavte double bonus; ... public void setBonus(double bonus){ this.bonus = bonus; } }
5.1.2 coverage method
Some methods in the superclass are not necessarily applicable to the subclass Manager. Therefore, a new method is needed to override this method in the superclass
When we want to call a method in a superclass instead of the method in a subclass, we can use the keyword super to solve this problem
super.getSalary();
You can add fields, methods, or override methods of a superclass in a subclass, but inheritance does not delete any fields and methods
5.1.3 constructor of subclass
public Manager(String name,double salary,int year,int month,int day){ super(name,salary,year,month,day); bonus = 0; } //The super keyword here means: "call the constructor method with n, s, year, month and day parameters in the superclass" //Since the Manager cannot access the private field of Employee, the parameters must be initialized by calling a constructor
The statement that calls the constructor with super must be the first statement of the subclass constructor
If the constructor of the subclass does not explicitly call the constructor of the superclass, the parameterless constructor of the superclass is automatically called
5.1.4 inheritance hierarchy
Java does not support multiple inheritance like C + +, but it provides the function of interface to realize multiple inheritance
5.1.5 polymorphism
is-a rule: it can be used to determine whether data should be designed as inheritance relationship
- Each object of a subclass is also an object of a superclass
- Superclasses can be replaced with subclass objects wherever they appear in the program. Subclass objects can be assigned to superclass objects, and vice versa
5.1.6 prevent inheritance: final classes and methods
A class that does not allow extension is called final. If the final modifier is used when defining a class, it indicates that the class is final
A particular method in a class can also be declared final. If you do, subclasses cannot override this method (all methods in the final class automatically become the final class)
The main reason for declaring methods or classes final is to ensure that they do not change semantics in subclasses
5.1.7 cast type
Manager boss = (Manager)e;
The only reason to cast is to use the full functionality of the object after temporarily ignoring the actual type of the object
5.1.9 abstract classes
You can declare a method using the abstract keyword, but you don't need to implement it
A class containing one or more abstract methods must itself be declared as an abstract class
Abstract methods act as placeholder methods, which are implemented in subclasses.
You can declare a class as an abstract class even if it does not contain abstract methods
There are two ways to extend an abstract class:
1. Some or all of the abstract methods in the abstract class remain undefined in the subclass, and the subclass is marked as an abstract class
2. Define all methods
Abstract classes cannot be instantiated
5.1.10 protected access
Four access modifiers in Java
- private: visible only to this class
- public: fully visible to the outside
- protected: visible to this package and all subclasses
- Default, no modifier: visible to this package
5.2 Object: superclass of all classes
Object class is the ancestor of all classes in Java. In Java, each class extends object, but it does not need to be written explicitly
5.2.1 Object type variables
You can use variables of type Object to reference variables of any type
In Java, only the basic type is not an Object; All array types, whether Object arrays or arrays of basic types, extend the Object class
5.2.2 equal method
The equals method in the Object class is used to detect whether an Object is equal to another Object. The equals method implemented in the Object class determines whether two Object references are equal
When defining the equals method in a subclass, the equals of the superclass is called first. If the detection fails, the objects cannot be equal (the superclass method detects whether two objects belong to the same class)
5.2.3 equality test and inheritance (difficult)
The Java language specification requires the equals method to have the following features:
- Reflexivity: x.equals(x) returns true for any non null reference X
- Symmetry: for any reference X and y, x.equals(y) returns true if and only if y.equals(x) returns true
- Transitivity
- Consistency: if the objects referenced by x and y do not change, repeated calls to x.equals(y) should return the same result
- x.equals(null) should return false for any non null reference x
java.util.Arrays; static boolean equals(xxx[] a,xxx[] b); //Returns true if the two arrays have the same length and the data elements at the corresponding positions are the same //The element types of the array can be Object, int, long, etc java.util.objects static boolean equals(Object a,Object b); //If both a and B are null, return true; If only one of them is null, false is returned; Otherwise, a.equals(b) is returned
5.2.4 hashoCde method
A hash code is an integer value derived from an object. Hash codes are irregular. If x and y are different objects, x.hashCode() and y.hashCode() will not be basically the same
Because the hashCode method is defined in the Object class, each Object has a default hash code, and its value is obtained from the storage address of the Object
The hash code of the string is derived from the content
The hash code of array type consists of the hash code of array elements
5.2.5 toString method
toString method: returns a string representing the object value
Most methods follow this format: the name of the class, followed by a field value enclosed in square brackets
java.lang.Object; Class getClass(); //Returns a class object containing object information boolean equals(Object otherObject); //Compare whether the two objects are equal, and the comparison content is the space pointed to by the object. To override this method in a custom class String toString(); //Returns a string representing the value of the object. To override this method in a custom class java.lang.Class; String getName(); //Returns the name of this class Class getSuperclass(); //Returns the superclass of this Class as a Class object
5.3 generic array list
The ArrayList class is similar to an array, but the array capacity can be adjusted automatically when elements are added or deleted
5.3.1 declaration array list
java.util.ArrayList; ArrayList<E>(); //Construct an empty array list ArrayList<E>(int initialCapaity); //Constructs an empty array list with the specified capacity boolean add(E obj); //Append an element to the end of the array list and always return true int size(); //Returns the number of elements currently stored in the array list void ensureCapacity(int capacity); //Ensure that the array list has enough capacity to store the given number of elements without reallocating the internal storage array void trimToSize(); //Reduce the storage capacity of the array list to the current size
5.3.2 accessing array list elements
The convenience of automatically expanding the container of array list increases the complexity of accessing element syntax. You need to use get and set methods to access or change the elements of the array
java.util.ArrayList; //Take class E as an example E set(int index,E obj); //Place the value obj at the specified index position of the array list and return the previous content E get(int index); //Gets the value stored at the specified index location void add(int index,E obj); //Moves the element back and inserts obj into the specified index position E remove(int index); //Delete the element at the position and move the following element forward. Returns the deleted element
5.3.3 compatibility of typing with the original array list
5.4 object wrapper and automatic packing
All basic types have a corresponding class, and the Ingeter class corresponds to type int. These classes are called wrappers.
The wrapper is immutable, and once the wrapper is constructed, it is not allowed to change the value wrapped in it. At the same time, the wrapper class is still final, so its subclasses cannot be derived.
var list = new ArrayList<Integer> //Declares an array list of integers, but cannot be declared with ArrayList < int >
Automatic packing and unpacking
- Wrapper types can be declared null, so auto boxing may throw a NullPointerException exception
- If Integer and double types are mixed in an expression, the Integer value will be unpacked, promoted to double, and then boxed to double
- Packing and unpacking is the work of the compiler
java.lang.Integer; int intValue(); //Returns the value of this Integer object as an int (overrides the intValue class in the Number class) static String toString(int i); //Returns a new String object representing the decimal representation of the specified value i static String toString(int i,int radix); //The return value i is based on the decimal representation specified by the radius parameter static int parseInt(String s); static int parseInt(String s,int radix); //Returns an integer represented by a string s. The specified string must represent a decimal integer, or the radix parameter specifies a decimal representation static Integer valueOf(String s); static Integer valueOf(String s,int radix); //Returns a new Integer object, initialized with an Integer represented by the string s. The specified string must represent a decimal Integer, or the radix parameter must specify a decimal representation java.text.NUmberFormat Number parse(String s); //Returns a numeric value, assuming a numeric value represented by a given String
5.5 method of variable number of parameters
//Let's take a look at the definition of the printf method: public class PrintStream{ public PrintStream printf(String fmt,Object... args) { return format(fmt,args); } }
The ellipsis here is "..." Is part of Java code, indicating that this method can receive any number of objects (except fmt parameters)
//A simple example code public static double max(double... values){ double largest = Double.NEGATIVE_INFINITY; for(double v : values)if(v>largest) largest = v; return largest; }
5.6 enumeration class
public enum Size { SMALL,MEDIUM,LARGE,EXTRA_LARGE }
The type defined by this declaration is a class, which has exactly four instances. It is impossible to construct a new object
If necessary, you can add constructors, methods, and fields to enumeration types
public enum Size{ SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL"); private String abbreviation; private Size(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } }
The constructor of enumeration is always private, and the private modifier can be omitted
All enumeration types are subclasses of Enum class
java.lang.Enum; //Suppose an enumeration type E exists static Enum valueOf(Class enumClass,String name); //Returns an enumeration constant with the specified name in the given class String toString(); //Returns the enumeration constant name int ordinal(); //Returns the position of the enumeration constant in the enum declaration, counting from 0 int compareTo(E other); //If the enumeration constant appears before other, it returns a negative integer; If this==other, 0 is returned; Otherwise, a positive integer is returned. The order in which enumeration constants appear is given in the enum declaration
5.7 reflection
5.7.2 introduction to declaring exceptions
There are two types of exceptions: non checking exceptions and checking exceptions.
For checking exceptions, the compiler will check whether you know the exception and are ready to deal with the consequences; Non checking exceptions, such as out of bounds errors or accessing null references, are non checking exceptions.
5.8 inherited design skills
- Place public actions and fields in superclasses
- Do not use protected fields
- Implementing "is-a" relationships using inheritance
- Do not use inheritance unless all inherited methods are meaningful
- When covering methods, ensure the expected behavior
- Use polymorphism instead of type information
- Don't abuse reflection