Why RTTI
package rtti;
import java.util.Arrays;
import java.util.List;
abstract class Shape {
void draw() {
System.out.println(this + ".draw()");
}
abstract public String toString();
}
class Circle extends Shape {
@Override
public String toString() {
return "Circle";
}
void sayHello() {
System.out.println("hello");
}
}
class Square extends Shape {
@Override
public String toString() {
return "Square";
}
}
public class Shapes {
public static void main(String[] args) {
List<Shape> shapeList = Arrays.asList(new Circle(), new Square());
// Everything in a container is treated as object hold , When it is removed, it will automatically change to Shape
for (Shape shape :
shapeList) {
shape.draw();
}
}
}
- RTTI The meaning of the name : At run time , Identify the type of a type
- The basic purpose of object-oriented programming is , Let the code manipulate only references to base classes , polymorphic
- Sometimes you need to manipulate unique methods of a particular class , And this is not available from the base class , This is the use of RTTI The meaning of
Class object
- Type information at run time is determined by Class Objects represent , Each class has one Class object , Contains class related information
- Whenever you compile a new class , It will be by jvm The class loader subsystem in generates a class with the same name Class object (.class)
- The class loader subsystem is a chain of class loaders , The native class loader loads trusted classes , Include java api class , You can also add extra class loaders
- All classes are first used ( When you create the first reference to a static member of a class ), Dynamic loading into jvm in . This explanation , Constructors are also static .
- Once a certain class Class Object is loaded into memory , It's used to create all the objects of this class
- Want to use type information at run time , You have to get to Class References to objects