Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bacis constructor doubt

 
Satish Kumar
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello friends ,
i m unable to understand the reason behind this error i get with construtor's . Well this is what i did
1.I first wrote the following code and the execution was fine.

----------------------------------------------------
class A
{
A()
{
System.out.println("CLASS A defualt CONSTRUCTOR");
}
A(int x)
{
System.out.println("CLASS A PARAMETRISED CONSTRUCTOR");
}
};
class B extends A
{
B()
{
super(5);
System.out.println("CLASS B defualt CONSTRUCTOR");
}
B(int x)
{

System.out.println("CLASS b PARAMETRISED CONSTRUCTOR");
}
};

class C
{
public static void main(String[] arg)
{
B b= new B();
}

};

O/ P :
CLASS A PARAMETRISED CONSTRUCTOR
CLASS B defualt CONSTRUCTOR
-------------------------------------------------------------------------------
In above example since in B's defualt constructor , i was explicitly calling super(5) , it forced the A'S parametrized constructor to be executed ignoring A's default constructor .

Now if i remove the A'S default constructor and executed the code , i get this eror (here is the resultant code)
------------------------------------------
class A
{
/*A()
{
System.out.println("CLASS A defualt CONSTRUCTOR");
}*/
A(int x)
{
System.out.println("CLASS A PARAMETRISED CONSTRUCTOR");
}
};
class B extends A
{
B()
{
super(5);
System.out.println("CLASS B defualt CONSTRUCTOR");
}
B(int x)
{

System.out.println("CLASS b PARAMETRISED CONSTRUCTOR");
}
};

class C
{
public static void main(String[] arg)
{
B b= new B();
}

};
o/ p :
test.java:20: A(int) in A cannot be applied to ()
{
^
1 error
--------------------------------------------------------------
Now in the first programe ( with default constructor) the prog was running fine , now if i remove this defualt constructor (which i m not using in any part of my programe ) y do i get above error.
Some 1 plzz clarify .
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The B(int x) constructor is implicitely calling the A() constructor. If you don't want it to, you need to explicitely call a different one using

super(some parameters);
 
Satish Kumar
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks to all those replies , i m now confident with constructors
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic