Advanced quizzes, Java casting object

The following Java exercise(s) are designed for advanced level developers. 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 Object Casting

casting-objects-red

Quiz 1: Up casting objects in Java

What does the following code do?

public class Super {

	protected int x = 5;

	public Super() {
		x ++ ;
		System.out.print("-" + method(7,3));
	}
	public int method(int i){
		return x + i - 4;
	}
	public int method(int i, int i2){
		return method(i) + i - i2;
	}
}

public class Sub extends Super {

	int x = 3;

	public int method(int i){
		return (x * 2) + (i + super.x);
	}
	public static void main(String[] args){
		Super s = new Sub();
		System.out.print("-" + s.x);
		Super sup = new Super();
	}
}

Select the correct answer.


Quiz 2: Casting objects in Java

What appears in the standard output when this program is invoked?

public class Super {

	protected int x = 5;

	public Super() {
		this(4);
		System.out.print("-" + method(7,3,2));
	}
	public Super(int i) {
		System.out.print("-" + method(i,2));
		x += 3;
	}
	public int method(int i, int i2){
		return i - i2 + x;
	}
	public int method(int i, int i2, int i3){
		return(i + i2 - i3 + x);
	}
}

public class Sub extends Super {

	int x = 3;

	public int method(int x, int x2){
		return (this.x * 2) + (x + x2 + super.x);
	}
	public static void main(String[] args){
		Super s = 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!

7 Comments

Add a Comment
  1. An answer from an expert! Thanks for couinibrttng.

  2. The advanced level is too difficult for me. I am curious to know whether other readers experienced the same.

    1. Stands back from the keyboard in amtanmeez! Thanks!

  3. I learn everyday from your articles and quizzes. Thanks for that!

    1. You are welcome!

      1. Fiindng this post solves a problem for me. Thanks!

    2. At last, somenoe comes up with the “right” answer!

Leave a Reply

Your email address will not be published. Required fields are marked *