Java Modifiers and Casting Reference
Java Modifiers
- Field
- access modifers
- public
- accessed from anywhere the class that contains it
- protected
- accessed only from within its class, classes in the same package as its class, and subclasses of its class
- private
- accessed only from within its class
- default (no access specifier)
- accessed only from within its class and classes in the same package as its class
- existence modifiers
- static
- one exists for the entire class, rather than one for each object of its class
- usage modifiers
- final
- cannot be changed (i.e., constant or read-only)
- Method
- access modifers
- public
- accessed from anywhere the class that contains it
- protected
- accessed only from within its class, classes in the same package as its class, and subclasses of its class
- private
- accessed only from within its class
- default (no access specifier)
- accessed only from within its class and classes in the same package as its class
- existence modifiers
- static
- exists to serve its class, not to serve individual objects of its class; as a consequence, static methods do not have access to instance variables, as instance variables belong to the individual objects; as a further consequence, static methods do not have access to this and super.
- usage modifiers
- final
- cannot be overriden
- abstract
- must be overriden to be useful
- Class
- access modifers
- public
- accessed from within any class
- default (no access specifier)
- accessed from within any class in the same package
- usage modifiers
- final
- cannot be extended (inherited)
- abstract
- must be extended (inherited) to be useful
four possible ways to mix and match superclass references and subclass reference with superclass objects and subclass objects:
- referring to a superclass object with a superclass reference is o.k.
- referring to a subclass object with a subclass reference is o.k.
- referring to a subclassd object with a superclass reference is safe. Such code can only refer to superclass members. If this code refers to subclass-only member through the superclass reference, the compiler will report a syntax error.
Instance methods from the superclass that are overridden by the subclass are not accessed when the superclass reference is used,
unlike the case for hidden data and hidden static methods. Regardless of the superclass reference used, the subclass's copy is accessed.
- referring to a superclass object with a subclass reference is a syntaz error.
the references of superclass must be cast in order to access the fields/methods of subclass objects