Over a million developers have joined DZone.

Java Quiz: Using Inheritance and Static Methods

A new quiz for advanced Java programmers on the behavior of Java inheritance and static methods.

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Last Week's Answer

ClassA classA = new ClassA(new ClassB(new ClassB().method(2)));

//1)
  new ClassB().method(2)
   //c)
  System.out.print(new ClassA().method()); //the method returns y=0
     //b)
  System.out.print(new ClassB(4).method(3)); //the method returns x+i=3+3=6
       //a)
System.out.print(i); i=4 ;
//2)
   new ClassB(new ClassB().method(2));
   new ClassB().method(2) returns x+i = 3+2=5
   new ClassB(new ClassB().method(2)) = new ClassB(5);
   System.out.print(i); i=5
//3)
   new ClassA(new ClassB(new ClassB().method(2))) = new ClassA(new ClassB);
     System.out.print(classB.method(1));
     classB.method(1); returns x + i = 3+1 = 4

The result is 46054.

This Week's Quiz 

Purpose

  1. Introduce some tricks and behaviors of Java inheritance and overwriting methods.

  2. Compare an instance variable with a static variable.

  3. Mind training for programmers to improve their imaginations and expectations. 

What is written to the standard output as the result of executing the following code?

public class MySuper {

    int x = 2;
    static int s = 3;

    MySuper() {
        x += 4;
    }
    MySuper(int x) {
        this();
        x += x + 20;
    }
    public MySuper method(){
        x += 35;
        return new MyClass();
    }
}
----------------

public class MyClass extends MySuper {

    public MyClass() {
        super(3);
        x -= 7;
        s += x;
    }
    public MySuper method(){
        x += 7;
        return super.method();
    }
    public static void main(String[] args){
        MyClass mc = new MyClass();
        mc.method();
        System.out.println(s);
    }
}


Let us know if you have any questions or comments on our quiz series, and as always, you can find Sar here

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
java ,quiz ,inheritance ,static methods

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}