February 3, 2011

How Constructors work in Java

Create a Class A with a no-arg constructor - print "In A constructor"
Create Class B as a subclass of A - put a constructor with one argument to this constructor - print "In B constructor".
Create Class C as a subclass of B.
In the main method create an object of Class C as follows,
C c = new C(); // Make this line work!

Solution


A.java

public class A {
   public A() {
      System.out.println("In A constructor");
   }        
}

B.java

public class B extends A {
   public B(int i) {
      System.out.println("In B constructor");
   }  
}

C.java


public class C extends B {
   public C() {
      super(3);       
      System.out.println("In C constructor");
   }        
}

Driver.java

public class Driver {
   public static void main(String[] args) {
      C c = new C();
   }
}

No comments:

Post a Comment