Java core technology (four): inheritance

1. Classes, superclasses and subclasses

  • The child class inherits the parent class, and there is an is-a relationship between the two. The child class has all the resources of the parent class and can add unique fields and methods.

  • Subcategories cannot be deleted.

  • Java does not support multiple inheritance.

  • Subclasses can override the methods of the parent class. Note that overriding and method overloading are different concepts. When overriding (overriding) a method, the visibility of the subclass method cannot be lower than the superclass method. In particular, if the superclass method is public, the subclass method must be declared as public.

  • How the subclass calls the superclass method: super. the name of the superclass method ().

  • How to call the super class constructor in the subclass constructor: super. super class name (parameter list), note that this code must be the first sentence in the subclass constructor.

If the subclass's constructor does not explicitly call the superclass's constructor, the superclass's default (no parameters) constructor will be automatically called.
If the superclass does not have a constructor with no parameters, and the subclass's constructor does not explicitly call the superclass's other constructors, the Java compiler will report an error.

  • Polymorphism: An object variable can indicate multiple actual types of phenomena is called polymorphism. The phenomenon of automatically selecting which method to call at runtime is called dynamic binding.

1. Polymorphism

  • In the Java programming language, object variables are polymorphic. A parent class variable can refer to either a parent class object or any subclass object.
  • However, you cannot assign a reference to a parent class to a subclass variable.
  • Warning: In Java, references to subclass arrays can be converted to superclass array references without the need for coercive type conversion. For example, the following is an array of managers

2. Dynamic binding

  As mentioned before, the phenomenon that an object variable can indicate multiple actual types is called polymorphism, and the phenomenon that it can automatically select which method to call at runtime is called dynamic binding.

  Let's look at the process of calling the method:

  • The compiler looks at the declared type and method name of the object. Suppose xf(param) is called, and the implicit parameter x is declared as an object of class C. It should be noted that: There may be multiple methods whose name is f but whose parameter types are different. The compiler will list all the methods named f in the C class and the methods named f in the superclass whose access attribute is public (private methods of the superclass are not accessible). At this point, the compiler has obtained all the candidate methods that may be called.
  • Overload resolution : Next, the compiler will look at the parameter types provided when calling the method. If there is an exact match with the provided parameter type among all the methods named f, then this method is selected. This process is called overload resolution. Since type conversion is allowed (int can be converted to double, Manager class can be converted to Employee; class, etc.), this process can be complicated. If the compiler does not find a method that matches the parameter type, or finds that there are multiple methods that match it after type conversion, it will report an error. At this point, the compiler has obtained the method name and parameter type that needs to be called.

However, the return type is not part of the signature, so when overriding the method, you must ensure the compatibility of the return type. Allow subclasses to define the return type of the overridden method as a subtype of the original return type. For example, suppose

  • If it is a private method, a static method, a final method, or a constructor, the compiler will know exactly which method should be called. We call this method of calling static binding.
  • When the program is running and the method is called by dynamic binding, the virtual machine must call the method of the class that is most suitable for the actual type of the object referenced by x. Otherwise, it will look for the method in the superclass of class D, and so on.

  A search is performed every time a method is called, and the time cost is considerable. Therefore, the virtual machine creates a method table for each class in advance, which lists the signatures of all methods and the methods actually called.

  It should be reminded here that if you call super.f(param), the compiler will search the method table of the implicit parameter superclass.

3. Prevent inheritance: final classes and methods

  Classes modified with final are forbidden to inherit; methods modified with final indicate that the method does not allow subclasses of the class to be overridden; all methods in the final class default to final methods.

  In early Java, some programmers used final key words in order to avoid the system overhead caused by dynamic binding. If a method is not covered and is short, the compiler can optimize it. This process is called inlining. For example, an inline call to e.getName() will be replaced with access to the e.name field. However, if getName() is overridden in another class, then the compiler will not know what the overridden code will do, so it cannot be inlined.

  Fortunately, the just-in-time compiler in the virtual machine has much more processing power than traditional compilers. This kind of compiler can accurately know the inheritance relationship between the classes, and can detect whether there is really an overriding given method in the class. If the method is short, frequently called, and not really covered, the just-in-time compiler will inline the method. What happens if the virtual machine loads another subclass, and the inline method is covered in this subclass? The optimizer will cancel the inlining of the overriding method. This process is slow, but it rarely happens.

4. Abstract class

  In order to improve the clarity of the program, the class itself containing one or more abstract methods must be declared as abstract.

abstract class Person{
    
    
	……
	public abstract String getDescription();
}

  • In addition to abstract methods, abstract classes can also contain concrete data and concrete methods. But try to make the abstract class not contain concrete methods.
  • Abstract methods act as placeholders, and their concrete implementation is in subclasses. However, some abstract methods or abstract methods may not be defined in the subclass, so the subclass must also be marked as an abstract class.
  • Even if the class does not contain abstract methods, the class can be declared as an abstract class.
  • Abstract classes cannot be instantiated; object variables of an abstract class can be defined, but it can only refer to objects of non-abstract subclasses.

5. Summary of access modifiers

  • Visible to this class private
  • Visible to all classes public
  • Visible to this package and all subclasses protected
  • This package is visible by default

2. Object class: the parent class of all classes

  You can use a variable of type Object to refer to any type of object.

1.equals method

  Detect whether one object is equal to another object, used to determine whether two objects have the same reference.

  When defining the equals method in the subclass, first call the equals of the superclass. If the test fails, the objects cannot be equal. If the domains in the superclass are all equal, you need to compare the instance domains in the subclass.

  The equals method in Java has the following characteristics:

  • Reflexivity: For any non-null reference x, x.equals(x) should return true.
  • Symmetry: For any reference x and y, if and only if yequals(x) returns true, x.equals(y) should also return true. If x and y do not belong to the same class, it may not be applicable.
  • Transitivity: For any reference x, y, and z, if x.cquals(y) returns true, yequals(z) returns true, and x.equals(z) should also return true.
  • Consistency: If the objects referenced by x and y have not changed, repeated calls to x.equals(y) should return the same result.
  • For any non-null reference x, x.equals(null) should return false.

2.hashcode method

The hash code is an integer value derived from the object. Hash codes are irregular. If x and y are two different objects, x.hashCode() and y.hashCode() will basically not be the same. Several communication channels are listed in Table 5-1.

3.toString method

Three, object wrapper and automatic boxing

  • Object wrapper:

  All basic types have a corresponding class. These classes are called wrappers: Integer, Long, Float, Double, Short, Byte, Character, Void, and Boolean (the first six classes are derived from the public superclass Number). The object wrapper class is immutable, that is, once the wrapper is constructed, it is not allowed to change the value wrapped in it. At the same time, object wrapper classes are still final, so they cannot be subclassed.

  Generics can be reference types but not basic types.

  • Automatic packing:

  List is a collection object, list.add(3) will automatically be transformed into list.add(Integer.valueOf(3). This process is automatic boxing.
  int n= list.get(i) will be automatically translated into int n=list.get(i).intValue(). This process is automatic unboxing.

  Finally, it is emphasized that boxing and unboxing are recognized by the compiler, not a virtual machine. The compiler inserts the necessary method calls when generating the bytecode of the class. The virtual machine just executes these bytecodes.

Four, reflection

1.Class

During the running of the program, the class that saves the runtime type information of the object is called Class.

	Employee e;
	……
	Class c1=e.getClass();//获取Class对象
	String classType=c1.getName();//获取e的类名,包含了包前缀
	String name=e.getName();//获取e的对象名
	Class c2=Class.forName(classType);//也可通过已知的类名获取Class对象
	Class c3=Date.class;//也可通过这种方式获取类对象
	Class c4=int.class;
	CLass c5=Double[].class;
	Object o=e.getClass().new Instance();//创建一个和e同类型的实例,调用的是默认构造器


2. Catch the exception

	try
	{
    
    
		//可能抛出异常的语句
	}
	catch(Exception e)
	{
    
    
		//处理器语句
	}

  Once an exception occurs in the try, the remaining part will be skipped and directly entered into the catch for processing; if there is no exception in the try, the part in the catch will be skipped.

3. Use the ability of reflection analysis class

  To put it bluntly, it is to get information about the domain, method, constructor, and access permission modifiers of the involved objects by calling the methods in the Class class. In this part, it is good to learn the part about Class in the Java API.

4. Use reflection to analyze objects at runtime

  Obtain the state of the object while the code is running. Take a good look at the API.

Guess you like

Origin blog.csdn.net/Tracycoder/article/details/112308310
Recommended