class FatherClass{
public int value;
public void f(){
value=100;
System.out.println("FatherClass.value= "+value);
}
}
class ChildClass extends FatherClass{
public int value;
public void f(){
super.f();
System.out.println("ChildClass.value= "+value);
System.out.println(value);
System.out.println(super.value);
}
}
public class TestInherit{
public static void main(String[] args){
ChildClass cc=new ChildClass();
cc.f();
}
}
这个程序可以编译运行,但是我有个疑问,FatherClass和ChildClass二个类都没申明构造函数,那么new一个cc对象时,子类的构造的过程中必须调用其基类的构造方法,若子类构造方法中没有显式调用基类构造方法,而基类中又没有无参的构造方法,则编译出错,为什么这个程序可以编译啊?
public int value;
public void f(){
value=100;
System.out.println("FatherClass.value= "+value);
}
}
class ChildClass extends FatherClass{
public int value;
public void f(){
super.f();
System.out.println("ChildClass.value= "+value);
System.out.println(value);
System.out.println(super.value);
}
}
public class TestInherit{
public static void main(String[] args){
ChildClass cc=new ChildClass();
cc.f();
}
}
这个程序可以编译运行,但是我有个疑问,FatherClass和ChildClass二个类都没申明构造函数,那么new一个cc对象时,子类的构造的过程中必须调用其基类的构造方法,若子类构造方法中没有显式调用基类构造方法,而基类中又没有无参的构造方法,则编译出错,为什么这个程序可以编译啊?
cc.value调用的是子类的value.因为子类重新定义的value.即覆盖了基类的value.
package test;public class Sub extends Super{
int a = 1;
public Sub(){
System.out.println("Csub");
a = 0;
}
public void setA(int a) {
System.out.println("setsub");
this.a = a;
}
public static void main(String[] args) {
Sub sub = new Sub();
System.out.println(sub.a);
System.out.println(sub.getA());
Super sub1 = new Sub();
System.out.println(sub1.a);
System.out.println(sub1.getA());
}
}
class Super{
int a = 8;
public Super(){
System.out.println("Csupper");
a = 9;
setA(2);
}
public int getA() {
System.out.println("getsupper");
return a;
}
public void setA(int a) {
System.out.println("setsupper");
this.a = a;
}
}