• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Extends will invoke constructor?

 
Ankith suresh
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package pk1;
public class SCJP11
{
SCJP11()
{
}
}
---------------------------------

package pk2;
import pk1.SCJP11;
class SCJP11Test extends SCJP11 //1
{

}

When i compile the SCJP11Test.java
i am getting following error

SCJP11Test.java:3: SCJP11() is not public in pk1.SCJP11; cannot be accessed from outside package
class SCJP11Test extends SCJP11
^
1 error

Why the error is displaying while extending..?
Compiler trying to access the constructor while extending the class?
I thought error will display only when trying to create the object.


(edit: no bangs in topic title look much better)
[ June 12, 2007: Message edited by: Barry Gaunt ]
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

suresh


In the package pk1 the class is public but the constructor not public,as i explained already in your previous post.

In pk2 you are extending ,so here the compiler checks the constructor of the super class ,it could not found that one,it will give compiler error.


Put the constructor in the package pk1 as public and try again.


AND ALSO TRY BY DECLARING THE CONSTRUCTOR IN THE CLASS SCJP11 AS protected

Thanks

Anil Kumar

[ June 12, 2007: Message edited by: anil kumar ]
[ June 12, 2007: Message edited by: anil kumar ]
 
Ankith suresh
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi anil
I got it.
So what i understood is ..............

Whenever we extending a class, compiler will check the super class's default constructor accessability . right?
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

suresh

Not the default constructor ,what it checks it depends on your program

say for example


class A
{
A(int a)
{
}
}

class B extends A
{
}


In this program if you try to compile class B you will get compile time erro,like there is no constructor of this type A(){}.

Because in the B class the compiler puts these for you

B()
{
super();
}


Means here the compiler checks wheather default constructor is there or not.Because super() calls default constructor.

B() //line 1
{
super(10);
}


If you right like line 1 this time the compiler checks wheather is there any constructor with single parameter of type int or float or long or double there or not.Because it knows it has to call a constructor of single parameter type.


Thanks

Anil Kumar
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thats correct Anil kumar!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic