Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

java - protected/public Inner Classes

Can someone please explain to me what is the difference between protected / public Inner classes?

I know that public inner classes are to avoid as much as possible (like explained in this article).

But from what I can tell, there is no difference between using protected or public modifiers.

Take a look at this example:

public class Foo1 {
 public Foo1() { }

 protected class InnerFoo {
  public InnerFoo() {
   super();
  }
 }
}

...

public class Foo2 extends Foo1 {
 public Foo2() {
  Foo1.InnerFoo innerFoo = new Foo1.InnerFoo();
 }
}

...

public class Bar {
 public Bar() {
  Foo1 foo1 = new Foo1();
  Foo1.InnerFoo innerFoo1 = foo1.new InnerFoo();

  Foo2 foo2 = new Foo2();
  Foo2.InnerFoo innerFoo2 = foo2.new InnerFoo();
 }
}

All of this compiles and is valid whether I declare InnerFoo protected or public.

What am I missing? Please, point me out a case where there's a difference in using protected or public.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The protected access modifier will restrict access from classes other than the ones in the same package and its subclasses.

In the example shown, the public and protected will have the same effect, as they are in the same package.

For more information on access modifiers, the Controlling Access to Members of a Class page of The Java Tutorials may be of interest.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...