Intermediate quizzes – Java abstract classes exercises

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

abstract-classes-blue

Quiz 1: Abstract classes in Java.

What happens when the following program is compiled and run?

public abstract class Base {

	int x = 2;

	public Base() {
		System.out.print("-x" + x);
		x ++ ;
	}
	abstract int calculate();
	abstract int calculate(int i);
}

public class MySuper extends Base {

	public MySuper() {
		System.out.print("-x" + calculate(2));
	}
	int calculate(){
		return x;
	}
	int calculate(int i){
		return i * x;
	}
}

public class Sub extends MySuper {

	int calculate(){
		return x + 2;
	}
	public static void main(String[] args){
		Sub sub = new Sub();
		System.out.print("-x" + sub.calculate());
	}
}

Select the correct answer.


Quiz 2: Abstract classes and methods

What happens when the following program is compiled and run?

public abstract class Base {

	int z = 6;

	public Base() {
		z -= 2;
		System.out.print("-z" + method(3,8));
	}
	abstract int method(int i);
	abstract int method(int i, int i2);
}

public class Sub extends Base {

	int z = 2;

	public Sub() {
		System.out.print("-z" + method(4));
	}
	int method(int i){
		return(z * i + super.z);
	}
	int method(int i, int i2){
		return(method(i) + i + i2);
	}
	public static void main(String[] args){
		Sub sub = new Sub();
	}
}

Select the correct answer.



Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!