-1

Within Java,

  • when to declare an object as "private final",
  • when to declare an object as "public"?

In the following code segment, String regex is declared as Private final

  • does it mean that it can only be used within the class RegexExcludePathFilter,
  • why accept can be declared as public.
  • What are the inherent design considerations?

enter image description here

Pshemo
  • 122,468
  • 25
  • 185
  • 269
user785099
  • 5,323
  • 10
  • 44
  • 62
  • 2
    So many questions. Can we at least know what do you think about it and what part confuses you? Have you read tutorials about methods, fields, access modifiers, final keyword, encapsulation? – Pshemo Mar 09 '14 at 15:00
  • private is used to be accessible within the class. final is used to initialize it at the time of object creation and can't be updated later. public is used if it is accessible outside the class or package. – Braj Mar 09 '14 at 15:03
  • possible duplicate of [In Java, what's the difference between public, default, protected, and private?](http://stackoverflow.com/questions/215497/in-java-whats-the-difference-between-public-default-protected-and-private) – krampstudio Mar 09 '14 at 15:04

4 Answers4

0

regex can only be read (not written, final) within a method of the class itself (not a child). public method can be called by anybody. The design goal is to expose some methods to be used by someone else, to define what are the entry point, your API. private are for internal beahvior.

krampstudio
  • 3,519
  • 2
  • 43
  • 63
0

accept is a public method, since it's part of the class' external interface or contract. The regex member is private since its an implementation detail, and there's no point of accessing it from outside the class. In other words, anything to do with what the class does should be public. Anything to do with how the class does something should remain private, so it can be changed without impacting the class' users.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

when to declare an object as "private final", when to declare an object as "public"?

If a variable/method will be used only in that class, then declare it with private access modifier, and if a field/method should be used by other classes, then declare it with public.

In the following code segment, String regex is declared as Private final

does it mean that it can only be used within the class RegexExcludePathFilter?

Yes, Private member can be access only within the class they declared.

why accept can be declared as public.

May it should be used from other classes.

What are the inherent design considerations?

It's all about information hiding.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
0

Final classes cannot be extended. Final variables must be initialized on instantiating the class or if they are static in a static initializer or inline. Final variables are generally something you need as a constant.

Mark Giaconia
  • 3,844
  • 5
  • 20
  • 42