Class, superclass, sub-class:
The subclass method cannot directly access the private domain of the superclass.
This and Super are not references and cannot be assigned to another object variable.
Super in the constructor of the application:
Public Manager (String N, double s, int., int month, int day) {
Super (n, S, year, month, day);
Bonus = 0;
}
The statement that uses Super to call the constructor must be the first statement of the subclass constructor.
If the subclass constructor does not display a constructor that calls the superclass, it will automatically call the superclass default (no parameters) of the constructor. If the superclass does not have a constructor with no arguments, and there are no other constructors that call the superclass in the subclass's constructor, the Java compiler will error.
An object variable can indicate that a number of actual types of phenomena are known as polymorphism. The phenomenon of choosing which method to call automatically at run time is called dynamic binding.
Polymorphic:
Each manager is an employee, a is-a relationship, so the manager can inherit from the employee.
Dynamic binding:
The process by which an object invokes an object method:
- The compiler looks at the declaration type and method name of the object.
- Next, the compiler looks at the type of arguments that are provided when the method is called.
- If it is a private method, astatic method,afinal method, or a constructor, then the compiler will be able to know exactly which method to call, We make this call a static binding. By contrast, the method that is called relies on the actual type of the implicit parameter and is dynamically bound at run time.
- When the program is running and the method is called with dynamic binding, the virtual machine must call the method of the class that best fits the actual type of the object referenced by X. if the x type is Dand There is no corresponding method in D, the corresponding method is found in the superclass.
When overriding a method, the subclass method cannot be less than the visibility of the superclass method. (otherwise the compilation cannot pass)
Block Inheritance:final classes and methods
if the class is defined by using the Final modifier indicates that the class is Final class, which is not allowed to be inherited.
method in a class is declared as Final , the method cannot be overridden in a subclass.
The primary purpose of declaring a class or method final is to ensure that they do not change semantics in subclasses.
To force type conversions:
A reference to a subclass is assigned to a superclass variable, which is allowed by the compiler. However, a reference to a superclass is assigned to a subclass variable, and a type conversion is required.
Manger boss = (manager) staff[1];
An error occurs at run time, throwing a classcastexception exception.
Before you make a type conversion, you should see if you can convert successfully.
if (staff[1] instanceofr Manager) {
Boss = (manager) staff[1];
}
If the type conversion cannot succeed, the compiler will not make this transition. Cases:
Date C = (date) staff[1]; A compilation error will occur because Date is not A subclass of Employee
Sum up:
- Type conversions can only be made within an inheritance hierarchy
- Before you convert a superclass to subclasses, you should use instanceof to check.
Abstract class:
Abstract class Person {
Private String name;
Public person (String N) {
name = N;
}
Public abstract String getdescription ();
Public String GetName () {
return name;
}
}
Employee and Student inherit person
Person[] people = new person[2];
People[0] = new Employee (...);
PEOPLE[1] = new Student (...);
for (person P:people) {
System.out.println (P.getname () + "," + p.getdescription);
}
P.getdescription () is legal, the variable p never references the person object, but instead refers to the GetDescription () method in the employee or student subclass.
Protected Access:
4 Access Modifiers:
- Only visible to this class--private
- Visible to all Classes--public
- Visible to this package and all subclasses--protected
- Visible to this package--default, no modifiers required
Protected: A subclass that is not in the same package as the base class can access only the protected members that it inherits from the base class, not the protected members of the base class instance itself.
Object: Super class for all classes:
The object class is the ancestor of all classes, and in Java each class is extended by it.
Equals method:
The Equals method in the object class determines whether two objects have the same reference. For most classes, it doesn't make sense, so in order to compare the state of two classes, you need to override the Equals method.
The Java language specification requires that equals have the following characteristics:
- Reflexivity: Non-null reference x,x.equals (x) should return True
- Symmetry of
- Transitivity
- Consistency: Repeated calls, results unchanged
- For any non-null reference, x,x.equals (null) should return FALSE.
Attention:
- If a subclass can have its own concept of equality, the symmetry requirement will force detection with getclass.
- If the concept of equality is determined by the superclass, then the instanceof can be used for detection, so that an equal comparison can be made between objects of different subclasses.
Write the Equals method recommendation:
- The display parameter is named Otherobject, and you later need to convert it to another variable called other.
- Detects if this and otherobject refer to the same object: if (this = = Otherobject) return true;
- Detects if Otherobject is null, if NULL, returns false
- Compares whether this and otherobject belong to the same class. If the semantics of equals are changed in each subclass, it is detected with GetClass, if (fetclass () = Otherobject.getclass ()) return false, otherwise instanceof detection is used, if (! ( Otherobject instanceof ClassName)) return false;
- Convert Otherobject to the appropriate type variable: ClassName other = (ClassName) otherobject;
- Now it's time to compare all the fields that need to be compared, use = = to compare the base type, and use equals to compare the object fields.
Hashcode Method:
A hash code is an integer value that is exported by an object.
The hash code for a string is the same as the hash code, which is exported by the content, so the content is the same. The string class overrides the Hashcode method.
The definition of equals and hashcode must be consistent: if X.equals (y) returns True, then X.hashcode () must have the same value as Y.hashcode ().
If there is an array type of field, you can use the static Arrays.hashcode method to calculate a hash code that consists of the hash code of the array element.
ToString Method:
Programmers who design subclasses should also define their own ToString method and add a description of the subclass domain. If the superclass uses GetClass (). GetName (), then the subclass can just call super.tostring ().
As long as the object is connected to a string by the operator "+", the Java compiler automatically calls the ToString method to get a string description of the object.
Int[] luckynumbers = {1,3,5,7,9};
String s = arrays.tostring (luckynumbers);
Results: [1,3,5,7,9]
Java.lang.Class
String getName ()//Returns the name of this class
Class Getsuperclass ()//Returns the superclass information of this class as a class object
Generic Array list:
arraylist<employee> staff = new arraylist<employee> ();
Java7 can be omitted in the following <Employee>,ArrayList<Employee> staff = new arraylist<> ();
Staff.add (New Employee ("Harry Hacker", ...));
Staff.ensurecapacity (100);
New ArrayList (//capacity) is 100
Staff.size ()//Returns the number of elements actually contained in the array list, equivalent to the a.length of array A
void TrimToSize ()//reduce the storage capacity of the array list to the current size
To access an array list element:
Staff.set (i, Harry); The set method can be used only if there are elements in the I position
Employee e = Staff.get (i);
Employeee = Staff.remove (n); All elements after this position move forward one position, and the size of the array is reduced by one. I must be between 0~size ()-1
Object wrappers and auto-boxing:
wrapper class corresponding to the base type: Integer,long,double,float,short,byte,character,void, Boolean. (the first six are derived from the public super-class number)
The object wrapper class is immutable, that is, once the wrapper is constructed, changing the value of the wrapper is not allowed. Object wrapper classes are also final, so they cannot be defined as subclasses.
The type parameter in <> is not allowed to be a basic type, so it is not allowed to write: Arraylist<int>, can be written as ArrayList <Integer> list = new arraylist<> ();
After Java SE 5.0, List.add (3) is automatically converted to List.add (integer.valueof (3)) and this transformation is called automatic boxing.
Conversely, when you assign an integer object to an int value, the container is automatically disassembled.
int n = list.get (i); translate into int n = list.get (i). Intvalue ();
Automatic unboxing can also be performed in an arithmetic expression:
Integer n = 3;
n++;
Java.lang.Integer 1.0
static int parseint (String s)
static int parseint (String s, int radix)
Java.text.NumberFormat 1.1
Number Parse (String s)
Methods with variable number of parameters:
public static double Max (double ... values) {
Double largest = Double.min_value;
for (double v:values) if (V > Largest) largest = V;
return largest;
}
Invocation: Double m = max (3.1, 40.4,-5)
Reflection:
The reflection mechanism can be used to:
- The ability to parse classes at run time.
- View objects in the run, for example, write a tostring method for use by all classes.
- Implementing a common array manipulation code
- Using the method object, this object is much like a function pointer in C + +
class:
Employee e;
Class cl = E.getclass ();
E.getclass (). GetName ();
You can also call the static method forname to get the class object that corresponds to the name.
String className = "Java.util.Date";
Class cl = Class.forName (ClassName);
The classname must be a class name or interface name, or a checked exception will be thrown at run time. When you use this method, you should provide an exception handler.
The third way to get a class object:
If T is an arbitrary java type, T.CALSS will represent the matching class object.
Class cl1= Date.class;
Class Cl2 = Int.class;
Class Cl3 = Double[].class;
A class object actually represents a type, and this type may not necessarily be a class. int is not a class, but Int.class is an object of class type.
Virtual machines manage a class object for each type, so you can use the = = operator to achieve the operation of two class object comparisons. Cases:
if (e.getclass () = = Employee.class) ...
E.getclass.newinstance (); Create an instance of the same type as E. The Newinstance method invokes the default constructor (a constructor with no arguments) to initialize the newly created object. If this class does not have a default constructor, an exception is thrown.
String s = "java.util.Date";
Object m = Class.forName (s). newinstance ();
If you need to supply parameters in this way to the constructor of a class that you want to create by name, do not use the above statement, and you must use the Newinstance method in the constructor class.
Ability to use reflection to analyze classes:
In the Java.lang.reflect package, there are three classes field, method, and constructor, respectively, that describe the class's fields, methods, and constructors. These three classes have a method called GetName, which returns the name of the project. The field class has a GetType method that returns a class object that describes the type to which the domain belongs. The method and constructor classes have methods that report the type of the parameter, and the method class has a way to report the return type. These three classes also have a method called GetModifiers, which returns an integer value that describes the use of modifiers such as public and static with different bit switches. Alternatively, you can use IsPublic, isprivate, or isfinal in the modifier class to determine whether the method or constructor is public, private, or final. You can also use the Modifier.tosting method to print the modifiers.
The Getfileds, GetMethods, and GetConstructors methods in class classes will return the public fields, methods, and constructors provided by the class, including the members of the superclass. The class Getdeclarefields, Getdeclaremethods, and Getdeclareconstructors methods return all fields, methods, and constructors declared in the class, including private and protected members, but not members of the superclass.
Constructors[] Constructors = cl.getdeclaredconstructors ();
Method[] methods = Cl.getdeclaredmethods ();
field[] fields = Cl.getdeclaredfields ();
To use reflection to parse an object at run time:
When you write a program, it's easy to see the domain you specify if you know the domain name and type you want to see. The reflection mechanism allows you to view object domains that are not yet clear at compile time.
The key method for viewing object fields is the Get method in the field class. If f is an object of Type field, and obj is an object of a class that contains an F field, F.get (obj) returns an object whose value is the current value of the obj field.
Employee Harry = new Employee ("Hary Hacker", 35000, 10, 1, 1989);
Class cl = Harry.getclass ();
Field f = Cl.getdeclaredfield ("name");
Object v = f.get (Harry);
Because name is a private domain, the Get method throws a illegalaccessexception.
The default behavior of the reflection mechanism is limited by Java access control. However, if a Java program is not under the control of the security manager, access control can be overridden. To achieve this, you need to invoke the Setaccess method of the field, method, and constructor objects. Cases:
F.setaccessible (TRUE); Now OK to call F.get (Harry)
The Setaccessible method is a method in the AccessibleObject class, which is a public superclass of the field, method, and constructor classes. This feature is provided for debugging, persistent storage, and similar mechanisms.
The Get method also has a problem that needs to be addressed. The Name field is a string that can be returned as an object. To return a field of type double, you need to use the GetDouble method in the field class. The threshold value is automatically packaged as double.
Call F.set (obj, value) to set the F field of the Obj object to the new value.
To write a generic array code using reflection:
Employee[] A = new employee[100];
A = Arrays.copyof (A, 2*a.length);
Implementation of the Copyof method:
The first method:
public static object[] badcopyof (object[] A, int newlength]) {
object[] NewArray = new Object[newlength];
System.arraycopy (A, 0, NewArray, 0, Math.min (a.length, newlength));
return newarray;
}
This method is not feasible because the new object[] array is created within the method and will not eventually be converted to the employee[] array.
Improved version:
public static object Goodcopyof (object A, int newlength) {
Class cl = A.getclass ();
if (!cl.isarray ()) return null;
Class ComponentType = Cl.getcomponenttype ();
int length = Araay.getlength (a);
Object NewArray = array.newinstance (ComponentType, newlength);
System.arraycopy (A, 0, NewArray, 0, math.min (length, newlength));
}
Int[] A = {1,2,3,4,5};
A = (int[]) goodcopyof (A, 10);
To be able to do this, you should declare the goodcopyof parameter as the object type and not as an array of objects (object[]). The shaping array type int[] can be converted to object, but cannot be converted to an array of objects.
Call any method:
There is an invoke method in the method class that allows you to invoke the method wrapped in the current method object. The signature of the Invoke method is:
Object Invoke (Object obj, object ... args)
The first parameter is an implicit argument, and the rest of the object provides an explicit argument.
For a static method, the first argument can be ignored, that is, it can be set to null.
Assuming that M1 represents the GetName method of the Employee class, the following statement shows how to call this method:
string n = (string) m1.invoke (Harry);
If the base type is returned, the Invoke method returns its wrapper type.
Assuming that M2 represents the Getsalary method of the employee class, the returned object is actually a double, and the type conversion must be done accordingly. You can use automatic unpacking to convert it to a double:
Double s = (double) m2.invoke (Harry);
You can find the method you want by calling the Getdeclaredmethod method and then looking at the array of methods objects that are returned. You can also get the method you want by calling the GetMethod method in class. Because a method of the same name exists, you must provide the parameter type of the method you want. GetMethod's signature is:
Method GetMethod (String name, Class ... parametertypes)
Cases:
Method m1 = Employee.class.getMethod ("GetName");
Method m2 = Employee.class.getMethod ("Raisesalary", Double.class);
If you provide an incorrect argument when invoking a method, the Invoke method throws an exception, and the Invoke parameter and return value must be of type object. For this reason, it is recommended that you use the method object when necessary, preferably using interfaces and internal classes.
techniques for inheriting designs:
- Placing public operations and domains in a super class
- Do not use a protected domain
- Implementing a "is-a" relationship using inheritance
- Do not use inheritance unless all inherited methods make sense
- Do not change the expected behavior when overriding the method
- Use polymorphism, not type information
- Do not use reflection too much.
Java Core Technology Fifth chapter inheritance