The following Java exercise(s) are designed for intermediate level programmers. If the level is too hard, then I recommend to select an easier one or you might consider reading my article about this topic, which offers a theoretical explanation including more exercises. Read More: Java Abstract Classes
Article: Java abstract classes Quizzes: Beginner Intermediate Advanced |
Quiz 1: Overwriting abstract methods
What is written to the standard output as the result of executing the following code?
public abstract class Base { int x = 3; public Base() { x += 2; System.out.print("-x" + x); x ++ ; } abstract int calculate(); abstract int calculate(int i); } public class SuperA extends Base { int x = 1; public SuperA() { System.out.print("-x" + calculate(2)); } int calculate(){ return x; } int calculate(int i){ return(calculate() + i); } } public class Sub extends SuperA { Sub() { x += 3; } int calculate(){ return x + 6; } public static void main(String[] args){ Sub sub = new Sub(); System.out.print("-x" + sub.calculate()); } }
Quiz 2: Extending an abstract class in Java
What appears in the standard output when this program is invoked?
public abstract class Base { int y = 5; public Base() { y -= 2; System.out.print("-y" + method(4,7)); } abstract int method(int i); abstract int method(int i, int i2); } public class Super extends Base { int y = 2; public Super() { System.out.print("-y" + method(4)); } int method(int i){ return(y * i + super.y); } int method(int i, int i2){ return(method(i) + i + i2); } } public class Sub extends Super { int method(int i){ return y * 2 + i; } public static void main(String[] args){ Sub sub = new Sub(); } }
Article: Java abstract classes Quizzes: Beginner Intermediate Advanced |
Suggested Articles
![]() ![]() ![]() |
Excuse me! I have a question. d. This code writes “-x5-x9-x10” to the standard output. I don’t why this int calculate(){
return x;
}
result = 7 ??? please explain. Thank you!!!
Here is the explanation. By creating objects of the subclass, the constructor of the superclassA is invokend and that invokes the constructor of its supercalss Base.
The following writes -x5
public Base()
{
x += 2;
System.out.print(“-x” + x);
x++;
}
By invoking the constructor of the superclass SuperA
The method calculate(int i) is invoked.
The method calculate(int i) returns the method calculate() without parameters which is overridden in the subclas. The parameter 2 will be added to the result as follows:
calculate() int the subclass returns 6 + x = 7 + the parameter 2 = 9.