Java Object-Oriented Approach
- Declare and instantiate Java objects including nested class objects, and explain objects' lifecycles (including creation, dereferencing by reassignment, and garbage collection)
- Define and use fields and methods, including instance, static and overloaded methods
- Initialize objects and their members using instance and static initialiser statements and constructors
- Understand variable scopes, apply encapsulation and make objects immutable
- Create and use subclasses and superclasses, including abstract classes
- Utilize polymorphism and casting to call methods, differentiate object type versus reference type
- Create and use interfaces, identify functional interfaces, and utilize private, static, and default methods
- Create and use enumerations
Rule(s)
- OO programming relies on the class/instance duality: a class is a data structure plus functions (operations or “methods” in Java), which act on local data (attributes or fields) only; an instance is a class incarnation (a.k.a. “object”) at execution time. In short, a class is a “mold” for to-be-created instances.
- OO programming in Java mainly leads us to reuse existing classes in the JVM or external libraries. In contrast, user-defined classes are built from the
class
keyword when the functionality required by an app. is absent.Example (reuse)
Example (user-defined class) Programmable thermostat app. here…
Attributes (a.k.a. fields) and methods (a.k.a. functions or operations) are foundational content of classes Rule(s)
- In OO programming, attributes aim at being hidden (Parnas' information hiding principle) to avoid any direct (unsafe) access from any code outside owners, typically third-party classes. Instead, methods are generally exposed. Only internal (reusable) computations are hidden, leading to inherent (“private”) methods.
- The Smalltalk programming language philosophy is interesting: attributes are by default not accessible while functions are. To create some access (read and/or write), getters and setters are required. Moreover, in Smalltalk, instance attribute names must start with a low-case letter while class attribute (
static
keyword in Java) names must start with a capital letter.Example (Smalltalk)
Rule(s)
- Java supports the encapsulation principle with the
private
andprotected
keywords. There is no reason at all to set attributes to thepublic
visibility except constant attributes (final
keyword).Example
Rule(s)
- In OO programming, operations (methods in Java) are either visible from outside or for internal use only (
private
modifier).Example
Rule(s)
- Parameter passing may be ruled by the
final
keyword.Example Parameter_passing.Java.zip
![]()
Rule(s)
- As many other languages (C++, JavaScript, Python…), Java allows the possibility of having a variable number of arguments for methods.
Example Covariance.Java.zip
![]()
Rule(s)
native
methods are written in C/C++ and next incorporated into Java.strictfp
methods allow computations (for real numbers) that are independent of real number representation on machines (see also here…).Class attributes and methods
Rule(s)
- Class attributes are identified by the
static
keyword. Instead of instance attributes, class attributes are shared among instances. In other words, one may also consider that class attributes belong to the class itself and the class' instances just get an access.Example
Rule(s)
- Class methods are also identified by the
static
keyword. Instead of instance methods, class methods deal with class attributes only.Example
Static initialiser
Example
Bad object-oriented programming
Example Bad_OO.Java.zip
![]()
![]()
Example
Variations on visibility
Rule(s)
- Visibility possibilities are
private
, “package” (default),protected
andpublic
. Note that the “package” visibility is not associated with any keyword.Example Covariance.Java.zip
![]()
Rule(s)
- Contrary to C++,
protected
also implies “package”! So,protected
in Java has implications for both descendant classes (inheritance) and classes in the same package, i.e., the same directory.- Contrary to Eiffel,
private
in Java is not “really” private…Example
Rule(s)
- Contrary to C++, Java classes have a visibility which is most of the time
public
. At most one class may be declaredpublic
in a file. Other visibility possibilities for classes are “package” andprivate
.Example
import
clause
Example
![]()
Rule(s)
- The
classpath
OS variable plays a central role. Accordingly, it must be set to values (directory paths); this may occur within UNIX for example in relation with figure above.Example
Package import using
static
Example (without
static
import)Rule(s)
- The
static
import construct allows unqualified access to static members.Example
Constructor Rule(s)
- Java supports the notion of block initialization along with that of constructor for a class. The constructor's name is that of the class; it is, by default, a “classical” function without arguments. Contrary to C++, Java has no destructor notion apart from garbage collection, which periodically releases unused (i.e. “no longer pointed”) objects. So, Java releases memory in a deferred way. Namely, collectable objects become free memory in the Java Virtual Machine -JVM-. Garbage collection in Java is associated with the
finalize
method injava.lang.Object
.- The Java compiler (like the C++ compiler) generates a default constructor for a class. However, one often requires constructors with arguments for initializations typically. Any user-defined constructor (with or without arguments) cancels the default one. For this reason, if one intends to keep a no-argument constructor then one needs its re-introduction!
Example
Rule(s)
- Having several constructors in the same class is named constructor overloading. Note that overloading also applies for common methods that have the same name and a variation on their arguments : number and/or types.
Rule(s)
- Inheritance is a foundation of OO programming. The principle behind inheritance is the fact that data structures are extended from existing ones. This amounts to adding attributes (structural inheritance) and/or methods (behavioral inheritance). The way of dealing with inheritance in Java is the use of the
extends
keyword. Note that Java supports single inheritance between classes and multiple inheritance between classes and interfaces, between interfaces as well.java.lang.Object
is the single root of Java inheritance graph, thus leading to an inheritance tree.Example of inheritance tree (in French)
![]()
Structural inheritance
Example Polymorphism.Java.zip
Behavioral inheritance
Example Polymorphism.Java.zip
Property extension
Example Polymorphism.Java.zip
Inheritance and constructors
Example Polymorphism.Java.zip
Overriding (redefinition)
Example Polymorphism.Java.zip
Rule(s)
- Accessing to properties of ancestor classes in Java obeys precise rules.
Example
Rule(s)
- Overriding private methods is impossible in Java.
Example
final
and inheritanceRule(s)
final
declared classes are not inheritable, e.g.,java.lang.Integer
.final
declared methods cannot be redefined.private
methods are implicitlyfinal
.Initialization protocol
Rule(s)
- The inheritance-based chaining of constructors must be under control to avoid undesired side effects.
Example Initialization_protocol.Java.zip
Rule(s)
- Anonymous classes have no name. They are created on the fly. Their main purpose is avoiding excessive inheritance, i.e., systematically creating descendant classes from other classes or interfaces.
- As an illustration,
java.util.TimerTask
is an abstract class. It has a singlerun
method that requires a definition through an inheriting class. Timers accept timer task objects as arguments for later executingrun
at key instants, e.g., each second. To avoid the creation of such a class (that involves the creation of an associated.java
file) for only definingrun
, an anonymous class may be useful.Example
Rule(s)
Anonymous_class_test$1
is the registered name of the anonymous class in the Java Virtual Machine -JVM-. The excessive use of anonymous classes leads to code, which might be maintainable with much difficulty.Double brace initialization
Rule(s)
- Anonymous classes may be created from double brace initialization as well.
Example
Rule(s)
- Polymorphism is intimately associated with inheritance. Polymorphism relies on the testing of objects' type at run-time to choose the “right” code.
Example Polymorphism.Java.zip
Rule(s)
- Polymorphism is strongly grounded on the fact that objects from “higher” types in the inheritance tree may dynamically “point/refer” to objects of lower ones (contravariance, line 2).
- The contrary does not apply apart from casting (line 5). In this scope, runtime errors may appear when types are incompatible.
Example
Covariance (on return types)
Rule(s)
- From Java 5, Java supports covariance (on return types). As a result, the following example shows that
cloning
in bothFemale
andMale
is really is considered as an overriding ofcloning
inIndividual
.Example Covariance.Java.zip
![]()
Rule(s)
- Covariance on return types is an original principle of the Eiffel OO programming language, which offers a graceful style compared to Java.
Example
Static method hiding using
final
Example Final_and_static_methods.Java.zip
![]()
Rule(s)
- The notion of interface is native from Java birth. Creating an interface creates a (reference) type.
- Up to Java 7, methods in interfaces are
abstract
andpublic
while attributes arepublic
,static
, andfinal
.- Interfaces are close to abstract classes having, up to Java 7, no concrete methods at all (declared or inherited). As an illustration,
java.util.Comparator<T>
is a famous predefined interface for comparing (e.g., sorting) “compliant” objects.Example
Interfaces: key issues
Rule(s)
- Interfaces are types. For example, the
java.lang.Integer
class implements thejava.lang.Comparable<T>
interface withT
equals tojava.lang.Integer
.Example
Rule(s)
- The key advantage of interfaces is the fact that predefined code may be written based on an anonymous
T
type. Later on,T
may be replaced by a known type provided that this type (e.g.,T
) complies withjava.lang.Comparable<T>
.Example Sort_illustration.Java.zip
![]()
Multiple interface inheritance
Example
Conflict about multiple interface inheritance
Example Multiple_inheritance.Java.zip
interface
changes from Java 8 and 9Rule(s)
- From Java 8, interfaces, like classes, may have
static
methods.- The other issue in Java 8 is the introduction of default methods using the
default
keyword as prefix. Due to the fact that default methods make interfaces and abstract classes very similar, a remaining difference is the fact that abstract classes have constructors while interfaces have not.- As of Java 9, methods may be declared
private
.Example (with misconception on line 41) From_Java_9.Java.zip
![]()
Example (old-school style)
Rule(s)
- From Java 5, enumerated types have a direct support based on
enum
keyword.Example
Rule(s)
- Enumerated types and sets are closely related in Java by starting from the
Enum<E extends Enum<E>>
interface and thejava.util.EnumSet<E extends Enum<E>>
class.Example Exception_management.Java.zip
![]()
Example