为什么默认构造函数在父类中是必需的(显式),如果它有一个有争议的构造函数
class A {
A(int i){
}
}
class B extends A {
}
class Main {
public static void main(String a[]){
B b_obj = new B();
}
}
Run Code Online (Sandbox Code Playgroud)
这将是一个错误.
我知道为什么a.get()返回20,这是因为动态绑定,因为B对象是在运行时创建的,所以它get()在类B中调用了
但是为什么要a.x打印10?
class A {
int x = 10;
int get() {
return x;
}
}
class B extends A {
int x = 20;
int get() {
return x;
}
}
class Main {
public static void main(String[] args) {
A a = new B();
System.out.println(a.get()); //20
System.out.println(a.x); //10
}
}
Run Code Online (Sandbox Code Playgroud)
如果您还可以在此处解释用于存储对象的内存。
考虑以下示例:
public class Main
{
public static void main(String[] args) {
System.out.println(new Maruti().howManyTires());
new Maruti().getColor();
}
}
Run Code Online (Sandbox Code Playgroud)
class Car {
private int tires = 1;
public int howManyTires(){
return tires;
}
public void getColor(){
getNiceColour();
}
public void getNiceColour(){
System.out.println("Blue");
}
}
Run Code Online (Sandbox Code Playgroud)
class Maruti extends Car {
private int tires = 10;
public int howManyTires(){
return super.howManyTires();
}
public void getColor(){
super.getColor();
}
public void getNiceColour(){
System.out.println("Magenta");
}
}
Run Code Online (Sandbox Code Playgroud)
输出为:
1
Magenta
Run Code Online (Sandbox Code Playgroud)
我的问题是,当howManyTires通过调用超类的函数时super,this引用显然是子类的(如对getColor …