|
Re: Inner class and access specifier and inheritance
|
Posted: Jan 9, 2003 11:06 AM
|
|
There is constructor access problem. Let me explain you the classes you have created. com.siva.simple.InnTestA has an inner class Ica. The class Ica is declared protected. When you compile the class InnTestA then it a default constructor for Ica is added by compiler which has access level of protected. So, the compiled com.siva.simple.InnTestA look like:
package com.siva.simple;
import java.io.PrintStream;
public class InnTestA
{
protected static class Ica
{
protected Ica()
{
}
}
public InnTestA()
{
}
protected static void Hello_prot()
{
System.out.println("InnTestA-Hello_prot");
}
}
Note that compiler also added a default constructor for InnTestA class with public access level.
Now, let us discuss the piece of code which is giving problem:
Ica a = new Ica();
Also note that in second example you have placed InnerD class in a default package. That is, InnerD class is not in the same package com.siva.simple as InnTesta class is. The left hand part of above statement is:
Ica a
Here you are declaring a reference variable a of type Ica. Since InnerD is inherited from InnTestA and Ica is a protected inner class in InnTestA, your declaration
Ica a
is valid. You can always access a protected member of a class in its subclass.
Now, let us move on to right hand side of your code:
new Ica()
Here you are accessing the default constructor Ica() of class Ica. What is the access level of Ica() constructor? It is protected. Recall that it was added by compiler. And, a protected member is available to only two: 1. To its subclass 2. In the same package
Since your InnerD is inherited from InnTestA and not from InnTestA.Ica, so the first case doesn't apply here. Since you have not placed InnerD class in com.siva.simple, so InnerD and InnTest.Ica classes are not in the same package.
Now, the result is you cannot access Ica() protected construcor. And, that is whay you are getting the compiler error in example 2. You can figure it out that your example 1 worked fine because you placed both classes in the same package and case 2 applies for example 1.
So, what is the solution? 1. Go ahead and change class InnTestA and add a public constructor to Ica as:
package com.siva.simple ;
public class InnTestA {
protected static void Hello_prot(){
System.out.println("InnTestA-Hello_prot");
}
protected static class Ica {
// Add this new line
public Ica() { }
}
}
2. Place your InnerD class in the same package com.siva.simple. That is, change your InnerD.java file to:
package com.siva.simple ;
class InnerD extends InnTestA {
public static void main(String[] args ){
Hello_prot();
Ica a = new Ica();
}
}
Note that now you don't need to import InnTesta class inside InnerD.java because both classes are in the same package.
Follow either method to compile your classes...
Thanks Kishori
|
|