On the Java Object class

Java Object class

  • Object class is a generic class, Java All classes inherit from the Object class out. Therefore, the process can be understood as creating an object

    public class Cars extends Object{
        // 继承Object
    }
  • Object class is not an abstract class, the method can be partially covered.

  • Object class has many useful methods

    • equals () compare two classes are equal
    • getClass () tells you where the object is initialized
    • hashCode () lists the hash code for this object
    • Name toString () lists the classes and we do not care about a digital
  • Object class action
    • As a multi-state so that the method can cope with various types of mechanisms
    • Java implementation period provided in the program code for the method any object has needed (for all classes can be inherited)

Object class explanation polymorphic

// 以下代码是合法的
ArrayList<Car> myCars = new ArrayList<Car>(); // 保存Car的ArrayList
Car BMW = new Car(); // 新建一个Car
myCars.add(BMW); // 装进ArrayList
Car M3 = myCars.get(0) // 将Car赋值给新的Car引用变量
    
// 于是学了Object后会设想,能不能填入Object使其可以保存任意一种ArrayList呢?
// 于是考虑能否这么写代码?
ArrayList<Object> myCars = new ArrayList<Object>();
Car BMW = new Car();
myCars.add(BMW);
// 目前的代码没有问题,但是再做以下操作便会发生问题
Car M3 = myCars.get(0);
// 编译器会报错,为什么呢?
// 放进去的是宝马,但是从ArrayList<Object>取出来的对象都会被当成是Object这个类的实例

In this way, we see the following piece of code it has become clear

// 这一段代码是不合法的
public void go(){
    Dog aDog = new Dog();
    Dog sameDoge = get Object(aDog);
}

public Object getObject(Object o){
    return o;  // 返回的是同一个引用,但是类型已经转换为Object了
}
  • Easy to see that the compiler is based on the reference type to determine which method can be called. In detail, the object will inherit from the parent class with everything down, regardless of the actual objects that represent each type will be an instance of Object. So in addition to its own type, it can also be used as Object to deal with. But what is quoted is what you can only call! The new sub-class method can only write a reference to a subclass call!

  • The following code, very obvious

    public class Dog{
        void yell(){
            // code
        }
    }
    Dog a = new Dog();
    Object o = a;
    o.equals(a); 
    >>> True
    // 二者的对象类型和地址都是相同的,因为这是赋值而不是在内存上开创空间
    o.yell();
    >>> Wrong
    // 这样会报错,因为引用的是Object类,里面没有yell()

Guess you like

Origin www.cnblogs.com/scyq/p/11604478.html