Create an inner class inherited with a secure access specifier

I wanted to do the following exercise from Bruce Eckel TIJ on inner classes:

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.

Here is my implementation:

first, the interface:

package workers;

public interface Employable {
  void work();
}

then a class with an inner class that implements the interface:

package second;

import workers.Employable;

public class WorkersClass {
    protected class Worker implements Employable {
        @Override
        public void work() {
            System.out.println("Hello, I'm a worker!");
        }
    }
}

and finally the inherited class:

package third;

import second.WorkersClass;
import workers.Employable;

public class Third extends WorkersClass {
    Employable getWorker() {
        return new Worker();//the line is reported to be incorrect
    }
}

IDEA underlines the line with Worker()in getWorkerand suggests making a class Worker public. But why? He advocated that successors WorkersClasscan instantiate a class Workerin their methods. Do I not understand something?

+4
source share
3 answers

The problem is not with the access specifier.

- , no-args

. , outer$inner inner , .

no org constructor :)

package second;

import workers.Employable;

public class WorkersClass {
    protected class Worker implements Employable {


        public Worker() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public void work() {
            System.out.println("Hello, I'm a worker!");
        }
    }
}
+3

WorkersClass

public class WorkersClass {
  protected class Worker implements Employable {

    public Worker(){}

    @Override
    public void work() {
        System.out.println("Hello, I'm a worker!");
    }
  }
}
+1

Third WorkersClass Worker.

Java , , Java 1.1. Worker "" WorkersClass, .
, Worker Third, Worker:

protected class Worker implements Employable {

  public Worker(){
  }

  @Override
  public void work() {
    System.out.println("Hello, I'm a worker!");
  }
}
0

All Articles