Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why does the child class need to implement the parent classes constructor?/

843789Dec 11 2009 — edited Dec 16 2009
As I was playing around with some code I came across this point :

First Class
public class A {
	public int x;
	A(int i){
		x=i;
		System.out.println("A is initialised");
	}

}
Second Class extending it :
public class B extends A{
	private int y;
   // Why do I need this constructor to call parents constructor?
  // My guess is so that when i make an object of class B referring to class A it should make sense?
	B(int i) {                      
		super(i);  
		y=test;
	}

	
public static void main(String args[]){
	 A a = new A(1);
	 A b = new B(1); make an object of class B referring to class A it should work!!
	 B c = new B(2);
	 B d =(B) new A(2);  --> gives class cast exception!
}
I am little confused here, Can someone throw more light on it.

Thanks
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 13 2010
Added on Dec 11 2009
26 comments
1,973 views