开发者

About Java Assignment Operator

开发者 https://www.devze.com 2023-01-08 00:32 出处:网络
If i define class A { public int a; public float b; public A() { a = 10; } } class B extends A { public B() {

If i define

class A {

public int a;
public float b;
public A() { 
a = 10;
}
}

class B extends A {

public B() {
a = 2;
}
}

class C extends A {

public C() {
b = 2.0f;
}
}

And in main

public static void main(//...) {

A a = new A();
B b = new B();
C c = new C();

a = b; //error?
b = c; //this one too?
开发者_开发百科

}


I am not sure about the first error, it looks fine. You should in future post the exact error message along it. You should never ignore error messages since they tell something about the cause of the problem. The second error is obvious, it's a type mismatch: C does not extends B, so you cannot assign an instance of C to a reference which is declared as B. To fix it, you should declare it as C, A or Object (since it is the implicit superclass of all classes).

Further, your class C doesn't compile since the constructor is named A() instead of C(), but that'll probably be a copypaste error ;)

See also:

  • Inheritance tutorial
0

精彩评论

暂无评论...
验证码 换一张
取 消