在面向对象的编程语言中,大部分不支持多根继承(Multiple inheritance)。仅有C++为了保证向后对于C的兼容性,支持多根继承。
在Java中,所有的对象最终都继承自一个单一的基类——Object。这种单根继承的好处是什么呢?为什么除了C++之外,几乎所有的面向对象的编程语言都采用了单根继承呢?
单根继承的好处:
- 在单根继承结构中,所有的对象都具有一个共用接口。它们归根到底都有相同的基本类型。(All objects in a singly rooted hierarchy have an interface in common, so they are all ultimately the same type)C++提供的继承结构无法确保所有的对象都属于同一个基本类型。从向后兼容的角度来看,这么做能更好地适应C模型。
- 单根继承结构保证所有的对象都具备某些功能,所有对象可以很容易地在堆上创建,而参数传递也得到了简化。
- 方便垃圾回收机制地实现。java的垃圾回收一般采用可达性分析,而单根继承结构使得寻找垃圾所在位置变得方便。
- 方便异常处理。写异常函数的时候不会因为不知道要抛出哪个异常类型而陷入僵局。给编程带来了极大的灵活性。
Object
Java的每一个类都由Object扩展而来。
public final native Class<?> getClass();public native int hashCode();
equals:
public boolean equals(Object obj) { return (this == obj);}
在Objects类中,equals方法将判断两个对象是否有相同的引用。 然而,对于多数类来说,这种判断没有什么意义。我们经常来检测两个对象状态的相等性,如果两个对象的状态相等,那么这两个对象是相等的。
下面代码介绍的是一个经典的equals方法:
class Student { ..... @Override public boolean equals(Object obj) { // checking if both the object references are // referring to the same object. if(this == obj) return true; // it checks if the argument is of the // type Student by comparing the classes // of the passed argument and this object. // if(!(obj instanceof Geek)) return false; ---> avoid. if(obj == null || obj.getClass()!= this.getClass()) return false; // type casting of the argument. Student s1 = (Student) obj; // comparing the state of argument with // the state of 'this' Object. return (s1.name == this.name && s1.id == this.id); } }
假如obj是Student的子类,使用下面这句代码会返回false
if(obj == null || obj.getClass()!= this.getClass())
r如果传递的参数是Student类的子类,则instanceof运算符条件不会返回false。
if(!(obj instanceof Geek)) return false;