相关疑难解决方法(0)

如果父类具有参数构造函数,为什么在父类中需要默认构造函数?

为什么默认构造函数在父类中是必需的(显式),如果它有一个有争议的构造函数

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)

这将是一个错误.

java

48
推荐指数
5
解决办法
7万
查看次数

A a = new B()在Java中到底是什么意思

我知道为什么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)

如果您还可以在此处解释用于存储对象的内存。

java object

2
推荐指数
1
解决办法
176
查看次数

Java:使用超级调用时,隐藏的超类字段的值是什么?

考虑以下示例:

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通过调用超类的函数时superthis引用显然是子类的(如对getColor …

java oop inheritance overriding

2
推荐指数
1
解决办法
61
查看次数

标签 统计

java ×3

inheritance ×1

object ×1

oop ×1

overriding ×1