I am reading Thinking In Java at the moment and I encountered one small problem. I am doing exercise 12 from chapter 8.
Create an interface with at least one method, in its own package. Create a class in a >separate package. Add a protected inner class that implements the interface. In a third >package, inherit from your class and, inside a method, return an object of the protected >inner class, upcasting to the interface during the return.
So I created these .java files:
A.java
package c08;
public interface A
{
void one();
}
Pr2.java
package c082;
import c08.*;
public class Pr2
{
protected class InPr2 implements A
{
public void one() {System.out.println("Pr2.InPr2.one");}
protected InPr2() {}
}
}
Ex.java
package c083;
import c082.*;
import c08.*;
class Cl extends Pr2
{
A foo()
{
InPr2 bar=new InPr2();
return bar;
}
}
And my NetBeans IDE underlines
InPr2();
and says that:InPr2() has protected access in C082.Pr2.InPr2 and I am wondering why. If I didn't explicitly state that constructor in InPr2 should be protected it would be only accessible in C082 package, but when I am inheriting class Pr2 shoudn't it be available in class Cl, because InPr2 is protected? Everything is fine when I change constructor to public.
Inner classesA inner class declared in the same outer class (or in its descendant) can inherit another inner class.
Ans. Inner Class is a class that is nested within another class whereas sub class is a class that extends or inherit another class.
A nested class may inherit from private members of its enclosing class. The following example demonstrates this: class A { private: class B { }; B *z; class C : private B { private: B y; // A::B y2; C *x; // A::C *x2; }; }; The nested class A::C inherits from A::B .
An inner class in Java is defined as a class that is declared inside another class. Inner classes are often used to create helper classes, such as views or adapters that are used by the outer class. Inner classes can also be used to create nested data structures, such as a linked list.
The constructor of InPr2
is protected, meaning that only classes inheriting from InPr2
(not Pr2
) can call it. Classes that inherit from Pr2
can see the class Pr2
, but they can't call its protected members, like the protected constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With