Java The following program would not compile. Why? (Assume the file name is B1.j
ID: 3824190 • Letter: J
Question
Java
The following program would not compile. Why? (Assume the file name is B1.java and you issued javac B1.java to compile.) Correct all errors so that the program would compile.
class A {
int a;
public A(int a) { }
public void m1() { }
final public void m2() { }
}
class B1 extends A {
int b;
public B1(int b) { }
public void m1() { }
final public void m2() { }
public static void main(String args[]) {
B1 objB = new B1();
A objA = new A();
objB = objA;
objB.m1();
objA.m2();
}
}
Explanation / Answer
i have corrected the code and compiling well, i have commented through out the code.
class A {
int a;
public A(int a) { }
public void m1() { }
final public void m2() { }
}
class B1 extends A {
int b;
public B1(int b) {
super(b);//need to call super constructor
//as its extending class A
}
public void m1() { }
//final public void m2() { } final method cannot overriden
public static void main(String args[]) {
B1 objB = new B1(6);//parameter required as no-arg constructor
// not defined in class B
A objA = new A(7);//parameter required as no-arg constructor
// not defined in class A
objB = (B1) objA;//casting to B1
objB.m1();
objA.m2();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.