Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inner class and inheritance

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.

like image 238
Andrew Avatar asked Aug 18 '11 23:08

Andrew


People also ask

Are inner classes inherited in Java?

Inner classesA inner class declared in the same outer class (or in its descendant) can inherit another inner class.

What is an inner class and how it is different from an inheritance?

Ans. Inner Class is a class that is nested within another class whereas sub class is a class that extends or inherit another class.

Can nested class be inherited?

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 .

What is an inner class in Java?

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.


1 Answers

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.

like image 157
RustyTheBoyRobot Avatar answered Oct 07 '22 13:10

RustyTheBoyRobot