1

Say you have a package-scoped class:

class MyClass {
}

What is the difference between

class MyClass {
    public f() { ... }
}

and

class MyClass {
    protected f() { ... }
}

and

class MyClass {
    f() { ... }
}

?

Since the class is package scoped, what will making the function public or protected do or add?

My reasoning for a package-scoped class:

  • You can't use the class from outside the package since it is package scoped, so public has no additional effect.
  • Following the same reasoning, protected has no additional effect, as you must stay within the package anyway.
  • Therefore, only private has limiting effect as the other 3 modifiers (package, public, protected) are all the same.

Is this correct?

I don't see the difference between the modifies when the class is package scoped.

Jade Dezo
  • 369
  • 3
  • 13
  • 1
    Possible duplicate of [In Java, difference between default, public, protected, and private](https://stackoverflow.com/questions/215497/in-java-difference-between-default-public-protected-and-private) – Nam Tran Nov 17 '17 at 08:28
  • 1
    @TrầnAnhNam I understand the difference between the modifies, but not when the class is package scoped. – Jade Dezo Nov 17 '17 at 08:30
  • In that article show the accessible by modifier in package scoped. Your class is package scope, but its sub class may be not. – Nam Tran Nov 17 '17 at 08:38
  • If a class is package scoped, how can you make a sub class from that class which is not in that same package? – Jade Dezo Nov 17 '17 at 08:39
  • @JadeDezo Tran mean, some public class X extends your package scoped Y class. That is allowed however still only private makes sense and remainin modifiers won't serve any purpose – Suresh Atta Nov 17 '17 at 08:43
  • 1
    If a public class `A` extends your `MyClass` in same package, and if class `B` in another package extends `A`, `B` can access public, protected member of `MyClass`. – Nam Tran Nov 17 '17 at 08:50
  • Oh right, I did not think about that. THANKS – Jade Dezo Nov 17 '17 at 08:51

1 Answers1

2

Yes. Though public and protected are redundant in default classes, still private have some meaning for them.

As pointed out in comments, in a inheritance cycle, though not directly, indirect children may get access through some other public class and hence they come handy in cases.

Otherwise, you already decided to make the whole class as package protected, apparently the inner level accessibility goes meaningless anyway.

In short you have chosen upper level against lower lever in terms of accessibility.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307