Java Inheritance Exercises

class A {}
class B extends A {
void print() {
System.out.println(super.getClass().getName());
}
public static void main(String[] args) {
B b = new B();
b.print ();
}
}
What is the output? Why? If you understand, talk about the following question:
class A {
int i = 1;
void print() {
System.out.println(i);
}
}
class B extends A {
int i = 2;
public static void main( String[] args) {
B b = new B();
b.print();
}
}
I'm not asking what the output is, but why is it output like this? Please help me~~~
采纳率:44% 11级 2013.08.10
哦 这个题目哦 最近在背面试题 刚好看到过...
第一题:
getClass().getName()方法,返回的是B类名
由于getClass()在Object类中定义成了final,子类不能覆盖该方法,所以,在B类方法中调用super.getClass().getName()方法返回的也应该是B自己的类名。

第二题:
b中未定义 print方法 所以直接调用的是从父类a里面继承的print方法。根据 就近原则自然调用的是a类的i,Java中重写指的是方法的重写,而不是属性的重写,还有 多态也只是方法的多态 ,没有属性的多态。确切的说java 没有属性的覆盖这一说法。属性是编译时候就确定了的,而所谓的覆盖方法则是运行的时候动态绑定的。在子类调用与父类属性同名的属性时应该说 “父类的属性被子类的属性挡住了”. 不过确实很 多人还是习惯叫“覆盖”,一些精辟的 概念,都需要精准的词来修饰,不然有可能大家都理解其中的概念,但是说给别人听 就全乱了 .... 楼主可不要被混淆了啊~

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324729473&siteId=291194637