Author Topic: [GUIDE] Java keywords (public, protected, private, final, static)  (Read 859 times)

Offline Tryskell

  • The cute dwarf
  • Administrator
  • Core
  • *
  • Posts: 3.798
  • Awards You don't like me, but I got the power. Forever dwarf.
A simple and basic Java lesson, keywords ! This topic can be fed or edited overtime.

PS : in this topic, an object is considered either a variable, a method, or a class.

Keywords meaning and main uses

It defines the visibility of the object. Public means it is reachable by any class, protected means there must have a link between classes, private means it's an internal object, usable only by this object (not reachable by children).

Main use : define and limit the scope of an object, which help you to understand faster the purpose of the object.

The object can't be re-allocated ; for a method, it means you can't override it, for a variable such as int it means you can't edit the value anymore, for a List/Map it means you can't dump the object, or replace the object by another (you still can .clear() the data from it or affect the data ; you simply can't DUMP the object HashMap or replace it by another new HashMap<>()).

Main use : mostly used as a security valve, as it tells you than the object can't be re-allocated. So you're SURE the object, once allocated, stays allocated (no null check needed, etc). In case of method, you are sure than children don't override it.

The object is shared amongst all generated objects, which avoid to generate one reference per clone.

Main use : correctly used for variable case, can seriously decrease RAM consumption of an object. In case of a method, it is generally used for "commons" task, where all parameters used by the method are given by method parameters and not based on class content.

Misc informations
  • You can use keywords on class, method or variable.
  • The order of keywords got no impact.
  • Only the static keyword, if correctly used, got an impact on performances. Other keywords are more about readability/safety.
  • enum is considered static by default, you don't need to define that keyword.
« Last Edit: January 04, 2017, 10:45:38 PM by Tryskell »
Code: [Select]
Triskel does not speak with foolish fellows who do not know their profession!

Offline minutis

  • Customer
  • Elpy
  • *
  • Posts: 14
Re: [GUIDE] Java keywords (public, protected, private, final, static)
« Reply #1 on: May 11, 2017, 12:35:44 PM »
One could add transient keyword to the list. In general it's used to prevent some fields from beeing serialized. One of the common use cases would be if you have some object and you want to convert it to json, then fields declared as transient would not be used while converting from/to JSON.