Java programming
Intermediate
1. SERIOUS OOP INHERITANCE POLYMORPHISM ......................................................................................... 3
1.1. INHERITANCE ....................................................................................................................................... 3
1.1.1. Access Modifiers ...................................................................................................................... 4
1.1.2. Test of know how classes can use inheritance (IS-A test) ........................................................... 5
1.2. POLYMORPHISM ................................................................................................................................... 5
1.3. CASTING OBJECTS AND INSTANCEOF OPERATOR............................................................................................ 6
1.4. TYPE SAFETY (TYPE SAFE LANGUAGE) .......................................................................................................... 8
1.5. METHOD OVERRIDING ......................................................................................................................... 10
1.6. METHOD BINDING ............................................................................................................................... 11
1.7. WHAT IS NOT OVERRIDDEN................................................................................................................... 12
1.8. OBJECT CLASS .................................................................................................................................... 13
1.9. CONSTRUCTOR CHAINING ..................................................................................................................... 14
1.10. PREVENTING INHERITANCE .................................................................................................................... 16
2. OOP ABSTRACT CLASSES INTERFACES .................................................................................................... 17
2.1. ABSTRACT CLASSES METHODS ............................................................................................................... 17
2.1.1. Abstract Classes ..................................................................................................................... 17
2.1.2. Abstract methods................................................................................................................... 18
2.1.3. Specifics ................................................................................................................................. 18
2.2. MULTIPLE INHERITANCE AND DIAMOND PROBLEM ...................................................................................... 20
2.3. INTERFACES ....................................................................................................................................... 21
2.3.1. Syntax.................................................................................................................................... 21
2.3.2. Conceptual View .................................................................................................................... 24
2.3.3. Marker Interfaces .................................................................................................................. 26
1. Serious OOP Inheritance Polymorphism
1.1. Inheritance
Motivation: there is same functionality for many classes for example class User and
classes Editor have 4 methods identical. All users can bookmark any item and can they
also read any bookmark. So there are duplicate codes. And duplicate code applies
maintenance nightmare (when we change in one method we need to update all four of
the class).
After inheritance the new design for this problem is:
Inheritance is one of the fundamental feature of OOP
Inheritance is subclasses inherit feature from subclasses and feature are basically
members that is variable and methods defined in super class are automatically part of
subclasses
Subclasses can access super class members directly
Super class can never access members of subclasses
This inheriting of members applies to only non private members of super class
Subclasses: is basically specialized version of super classes. They can
Inherit super class features
Add new members
Override super class methods: redefining behavior that is they can change or
extend super class behavior
Would inherit members from all its super classes in the hierarchy that is inheriting
members is not restricted to only its direct superclass
Terminology:
Super class: super type or base class
Subclass: subtype or derived class
In java, we can use inheritance by using keyword “extends” like these examples
In java, a class can extend from only one class
1.1.1. Access Modifiers
This part is about what members of a super class can be inherited by subclasses and these
declared by access modifiers defined for those members
Inheritance accessibility:
Private: not inherited
Default: inherited if from family(classes in same package) only family can access
inherited members
Public: inherited any one can access inherited members
Protected:
o Same access level as default members but allow access to subclass outside
the package
o Protected allow access to
All Family members (classes in the same package)
All subclasses inside/outside the package
1.1.2. Test of know how classes can use inheritance (IS-A test)
IS-A test is the first and the most fundamental test for inheritance that you need to
apply to determine if 2 classes can be related via inheritance
Staff IS-A user? Mean staff is a specialize type of user if this question is true so they can
be related via inheritance
HAS-A test: (bookmark HAS-A review)
If HAS-A test is true so this relationship is a composition (is preferred over
inheritance)
1.2. Polymorphism
Polymorphism is exist when existing inheritance that is because we have inheritance, we
are able to take advantage of polymorphism
Every class define a contract into its methods that is it and says that “I have these kinds
of methods”
o If the class is public and if it has public methods then the contract is the API
If class is a super class then its contract is also defining a common protocol for all its
subtypes that it is announcing that “book myself and all my subtypes have these kinds of
methods”
With polymorphism a super types can be assigned any of it subtypes
We can pass instance of any subclasses of the super class User because we can do
with subclass any action that we can do with super class. The benefits of that are:
Flexible code
Clean code
With polymorphism, reference type and actual object type can be different ( can do only
with 2 class inherited)
Compiler uses reference type to decide whether a method can be invoked
JVM in run time uses object type to decide which method is invoked
o JVM invokes most specific version of method in the inheritance tree
starting from object type
1.3. Casting Objects and instanceof Operator
Primitive casting (any primitive type other than Boolean):
Implicit: smaller variable to a larger variable
Explicit: larger variable to smaller variable
Now, with polymorphism we can assign variable of 1 class to variable of another class So
we also need casting here.
We have also 2 types of casting:
Implicit casting: subclass is implicit casting with a super class when we have
pass subclass object as argument with a method parameter which of type super
class like this example:
Using this type of casting we cannot use methods of subclass and not defined in super
class (cannot use any method specific to subclass)
Explicit casting: we can use subclass specific methods with this type of casting.
It’s same like implicit casting but with you can use subclass methods. You can use
explicit casting like this:
When you use explicit casting in method for example from Staff to Editor and when you
call the method you pass Staff object, so you have runtime error called
ClassCastException. This exception because Staff can be an Editor and Editor cannot be
Stuff (Inheritance) like this example:
‘Instanceof’ operator: this operator is the solution for the exception of
ClassCastException.
Usage: this operator do a simple test if the object instance in the left is an instance
of specific class on the right or not
Syntax:
Characteristics:
Object’s type is what matters: this operator test the object’s type
The instance of subclass is also an instance of its super class
Examples:
1.4. Type safety (type safe language)
Type safety is the extent to which a programming language prevents something called
type errors
Type errors: are certain of kind of errors that could lead to undesirable program
behavior. For example:
Invoking non-existent method on an object (java compiler not allow this but there
are same non type safety language could allow this)
Buffer overflow (out of bound writes). For example there are same language
allow this kind of error like this
There are many type of type safety enforcement:
Compile time (static type checking): there are same language do type safety
only in compile time like C and Pascal
Runtime (dynamic type checking): there are same languages do type safety only
in runtime like Ruby and python.
Both: there are same language do type safety in compile time and in runtime
Java is both compile time as well as runtime
Static type checking examples in java
Many of compile time errors before Java 5 where only caught at runtime but with the
introduction of generics and Java 5 many of those errors are caught at compile time
Dynamic type checking example in Java:
So only the ones of errors that cannot be prevented at compile time are they can get off at
runtime?
Java use static and dynamic type checking and considered as type safe language
Also note that since static type languages do all the checks at compile time itself and do
not need any additional checks at runtime they can still be faster than dynamically typed
languages
1.5. Method Overriding
Method overriding is redefine behavior of super class method and it could mean few
thinks:
Add new behavior: that is the overriding method does something different which
is specific to subclass
Extend behavior of the super class method: that is you would do what you want
the super class method does and then you would do something more
Providing better implementation: e.g. override bad code
Fulfilling the contract (remplir le contrat): we know the super class define contract
throw its methods and consequently define a common protocol for all its subtypes. So
when you override method from super class, you are agreeing to fulfill the contract
Method overriding rules: there are 3 rules for method overriding to work
Rule 1 - Same Name: Have the same letter name
Rule 2 – Same parameters + compatible return type:
o Return type must be same or subclass type
Rule 3 – can’t be less accessible:
o Access level must be same or friendly: for example you cannot override
public method and make it private
Also you have compiler error when you cannot do Rule 3
Super keyword: it can be used to access super class method from a subclass and it
typically used for extending behavior defined in super class. If the method in super class
is:
Non overridden: then it can be either accessed
o Directly: using the method name. its recommended (typically)
o With super keyword
Overridden: you must use super keyword to access to this method
Super keyword cannot be used in static method because it related to objects
Super keyword used then to access to hidden field (field name used in the subclass)
1.6. Method binding
It’s related to how method get executed
Every time you see a method call that is method binding and as the name suggests
It’s a mechanism of associating a method call in Java code to the declaration and
implementation of the method being called. So there are 2 distinct steps off method
binding
Method signature binding:
Step1: Compiler checks if reference type has compatible method: Once the
compiler encounters some method invocation statement, it checks the reference
type of the object reference on this method has been invoked includes compatible
method which include same or compatible parameters
Step2: Writes method signature details into byte code: If finds one then it
writes the method signature information into the byte code. Otherwise we know
that it throws a compiler error.
Rq: Applies to both instance or static methods: this is always done by the
compiler it doesn’t matter the method is static or instance
Method implementation binding:
Static method:
o the decision is made at compiler time itself (by compiler)
o it still based on reference type
Because it class method and don’t do anything with objects
Instance method:
o the decision is made at runtime by the JVM
o it based on the object type
o JVM invokes the more specific version of the method
Field binding: field are early bounded
1.7. What is Not Overridden
There are many items of class that cannot overridden:
Final method: it’s a normal method but it’s declared with the keyword final in its
declaration. That is the subclasses should ever be able to redefine it
You use when you have same implementation login and you need to cannot change it
Field (instance and statics): because fields are represent data of the class
Static methods: because if we have polymorphism station and we have static
method overridden then when we call this method the compiler will call the static
method of reference type So we don’t care about overridden with static methods
because it’s class method and not object method
Static methods and overriding:
Can’t be use super keyword in static method:
o To call same behavior of super class in static method then you need to
qualify the method name with the super class name (super class name
followed by dot operator and method name.
Can’t hide instance method: we get compiler error when we try to do this
Can’t be overridden by instance method: once again we get a compiler error if
you try to do this
1.8. Object Class
Object class is the mother of all classes and by that we mean that it is the super class of
everything that is every class directly or indirectly and implicitly extends the object class
Object class is in java.lang package
There are 2 reasons for having the object class
It act that polymorphic type: that is you can assign any java object to a variable
whose reference type is object class
Includes many core methods that are inherited by every class. There are methods
we can be used directly or overridden and other are marked as final
Core methods:
toString():
o it return string representation of object
o by default it include the class name on same number as we can see here
o item 10: Always override toString the raison for this is:
it’s very useful for debugging
it’s automatically called we pass object to system.out.println
statement
it should return all interesting information contained in the object
hashCode():
o returns object’s hashcode (memory address in hexadecimal)
o 2 object differences pointing to the same object will have the same hash
code
o Used in hash tables
Equals(object):
o Tests object equality and it return true if they are equal
o By default this method uses the equality operator ( it return true if objects
references is true)
getClass():
o it’s final method that return Class object which encapsulate all the meta
information about the class that is class of the object on which this method
is in work
o meta information include details like class name, super class name,
method names, …
clone():
o protected method that returns a copy of this object
o it must be overridden if we want to use its functionality
1.9. Constructor Chaining
Motivation:
We know that subclasses inherit methods from super class and those methods
might depends on super class state. There is instance variables that are define in
super class
Super class’s state should first be initialized. Otherwise you may create an object
and when you invoke an inherited method it might not work as expected as a state
in super class in not initialized
Constructors used to initialize state
All the super classes’ constructors should run before the subclass constructor this is
what constructor chaining does
Super keyword:
We can use super keyword to invokes super class constructor however the super
keyword will be followed by parenthesis which mean how zero or more
arguments super([arguments])
The super invocation statement must be the first statement in the constructor
unless (sauf si) at this() invocation is used
Constructor can have either this invocation statement or super invocation
statement but never both
With overloaded constructors and if they happen to invoke each other than the last
invoked constructor would be responsible for invoking super class constructor
If not provided, the compiler inserts no arguments super(). If not exist not
argument constructor in super class, then compiler error will generate
If for any reason a super class constructor cannot be invoked then compiler
error is generated
1.10. Preventing Inheritance
Why you want to prevent inheritance:
All methods are final
Class semantics(invariants) is final like string. You don’t have any sub classes
created
We have 2 methods to prevent inheritance:
Mark class as final:
o Final keyword is used in class declaration then this class can never be
extended. It also means that none of its methods can ever be overridden
o No extendible but instantiable. Like string class
You can use this method when you want to your class cannot extended (inherited) but you
can instantiate
Private constructor:
o Not extendible and not instantiable
o Item 4 : Enforce noninstantiability with private constructor
o Raison for not extendible: Cannot be invoked from subclass
No constructor chaining -> Subclass cannot be created
2. OOP Abstract Classes Interfaces
2.1. Abstract Classes Methods
2.1.1. Abstract Classes
It is a class that is too abstract (signifies abstractness) which means that :
Not instantiable: it include one or more methods on which it is not possible to
provide any implementation
It defines a common protocol for all its subclasses. It defines a contract and can
be used polymorphically
It define with key words “abstract” like this:
So the compiler will ensure that this class will not be instantiable
Abstract class has no use unless it is extended
It may exist though defined only static members but that cannot be the only purpose of its
existing and it would also be very confusing
With an abstract class, it is the instances of its subclasses which are doing the real work at
runtime
Declaring a class abstract only means that you don't allow it to be instantiated on its own
2.1.2. Abstract methods
It cannot have anybody (any implementation). Its implementation will provided by
subclasses
It must be overridden!
Can’t be static
Abstract method define with inserting keyword “abstract” in the method declaration like
this:
Declaring a method abstract means that subclasses have to provide an implementation for
that method.
2.1.3. Specifics
We cannot have an abstract method in a non abstract class. If there is even one abstract
method then the class must be abstract
Abstract class also contain :
One or more concrete methods that is methods with implementations
One or more abstract methods
Without any abstract methods: Need not have any abstract methods but that is
not typically done and it would be very confusing to have class without any
abstract methods
Abstract subclass: when super class is abstract, the subclass can also be abstract
Doesn’t have to ( )ال يجب أنoverride and inherited abstract method. But you can
override one or more of inherited abstract methods
doesn’t have to ( )ال يجب أنredeclare inherited abstract method
can override concrete methods
can define abstract and concrete methods
Concrete subclass:
Must override unimplemented abstract methods: must implement all methods that
not be implemented in all subclasses in the inherited tree. Otherwise we get
compiler error
Item 20: Prefer class hierarchies to tagged classes.
Example of tagged class:
Don’t use tagged classes for many reasons:
o Verbose: because you have multiple constructors to many fields and to
much of logic and one single method
o Error prone: you are trying to represent too many things in the same
class
Class will be designed with single responsibility principle
o Inefficient: increase memory as any object include irrelevant feats (fields
of others types of tag field)
Tagged to class hierarchy: We want to refactore our bookmark class
2.2. Multiple Inheritance and Diamond Problem
problem of common protocol:
Multiple inheritance could help us solve the technical requirement
Example of design with multiple inheritance and resolving the problem of common
protocol of classes “Book” and “WebLink” only
Java doesn’t support multiple inheritances because when you support multiple inheritance
you have a problem called diamond problem.
Diamond problem: To understand diamond problem, let’s consider this classes diagram
which incorporate multiple inheritance
Problem is which version of “isKidFriendlyEligible” method (same problem for
inherited fields) is inherited by “MovieAndBook” class
Answer is the programming language needs to support some complicated rules to
address this ambiguity.
Java we know is designed to be simple, so it does not supported multiple
inheritance
Technical requirement: common protocol for defining optional capability
getItemData() in only “Book” and “WebLink”
common protocol
Solution is with interfaces
2.3. Interfaces
Interfaces help in defining optional capability without compromising on polymorphism
Interface characteristics
It’s a reference type
It never can be object type. Non instantiable
In general term type in java is often used to refer to class or interface
2.3.1. Syntax
Defining interface: by using keyword interface like this
An interface is implicitly 100% pure abstract class (all methods are abstracts)
Can include keyword abstract in declaration of interface and the compiler will not
complain but that is redundant
Access modifiers: you have 2 type of access modifiers with interface
Public: access by all classes
Default(without any keyword): access only in the package
Default access modifiers:
Methods: public and abstract by default
Fields: public, static and final by default
All members are public by default
Members can’t be private or protected
Specifies default access to interface members:
If interface has default access, So public access level of interface members no
applies on those members are no visible outside of the package
Public access level of members is overridden by the default access level specified in
the interface declaration.
Class or interface can have only public or default access levels
Interface members:
Static final fields
Abstract methods
Default methods (java 8) concrete methods
Static methods (java 8) concrete methods
Nested types (nested classes or nested interfaces)
All these members are implicitly public
Implementing interface:
By using keyword implements
Implement multiple interfaces: you can implement many interfaces for same class
like this
Abstract subclass can also implement interface
Abstract subclass need not to implement abstracts methods inherited from interface
By using interface, you have polymorphic benefits of multiple inheritance
Extending interface:
Interface can extends another interface by using keyword extends
Same characteristics of extending of class, sub interface will inherits behaviors of
super interface and add same specifics behaviors
The class who implement sub interface, has to implement all the abstracts methods
declared and both the sub as well as super interface
An interface can extends multiple interfaces like this:
Implement 2 interfaces with same method:
If method is abstract in all super types, then you need to implement in subclass
We have not problem of diamond in this case, because in these problem we inherit
identical method from many super class but with implementations
If method is abstract in one (class A) and concrete in other (class B), not need to
implement the abstract methods from class A, the implement in class B would be
sufficient
Why fields are static and final?
Static?
o Because interfaces are not intantiable then they cannot have instance
variables
o Accessed by qualified name of interface
Final?
o To avoid diamond problem with shared state
Variable naming clash
2.3.2. Conceptual View
Interfaces are classified into 2 types:
Representative interfaces
o Define representative behavior of subclasses: define a code functionality of
subclasses
o Include one or more implementations
o Public API: rarely sub classed outside API
o Its common protocol to force programmer to provide an implementation
o Example:
Mixins
o Define certain capability that subclasses can have: subclass have their own
identity but in addition when they implement a mixing they’re also
announcing that they additionally support the capability that the mixin
interface is defining
o Very generic subclasses can come from anywhere
Multiple capability: example of class that is implement multiple capability
Comparable: have capability to compare it with any object
Cloneable: have capability to return their own copies
Item 18 Prefer interfaces to abstract classes
When to prefer interfaces:
o Mixins: interfaces are ideal to define mixins interfaces because it is
additional capability and class can support multiple of them
o Representative behavior with no state: for same raison because abstract
class cannot be extended by class that is extend other class
o
Principle reason for using interfaces is that java doesn’t support multiple
inheritances
When to prefer abstract classes:
o Core identity for subclasses: representative behavior with state like
bookmark class
o Skeletal implementation: that is that would implement interface and would
provide same of basic implementations
Naming convention of skeletal implement. “AbstractInterfacename”
Use utmost care when designing interfaces ()توخي أقصى درجات الحذر:
o If the code you write is using only within your organization then most likely
you are fine.
o If you are designing a public API then you should
Brainstorm quite a bit on the method signatures.
Once the API is released and widely used it would be extremely
difficult to make any changes that if you add any new method in
one of your interfaces in a subsequent release then any kind of
code that implement this interface will not compile anymore
Item 52 Refer to objects by their interfaces
Try to use interface as a reference type in all kinds of variable declarations and
also use them as method return types because this raison in the picture
Benefits :
o Can change implementation if needed
o Use implementation with better performance
o Polymorphism benefits
Maximum flexible code: with interfaces objects can come from
any inheritance hierarchy that is they need and this general not
possible with concrete or abstract classes as classes are
implementation specific and typically confined to one inheritance
tree
Clean code
Exceptions:
o No interface use least specific class
o Specific subclass functionality is needed
2.3.3. Marker Interfaces
Marker interface is an empty interface (no field or methods)
It’s an interface with no method declarations. They just tell the compiler that the objects
of the classes implementing the interfaces with no defined methods need to be treated
differently. These Marker interfaces are used by other code to test for permission to do
something.
They simply interfaces:
Without any methods that is they have empty body
Used to marks a class as having some property: any class implement this interface
then they have some property defined by this marks interface
It’s only plain English words and there are no methods
Examples:
Java.util.RandomAccess: any class implement this interface it’s allows a fast
random access of its elements
Java.io.serializable: any class implement this class it’s allows its objects to be
serialized and it allow objects to be converted to byte streams so that byte streams
can be saved to hard disk for later deserialization or byte streams can also
transmitted to a remote JVM
java.lang.Clonable: objects clone method may be called. So to clone object you
need to use this method in picture
If you not implement the marker interface Cloneable and try to clone object by
Object class clone method then compiler will throw “CloneNotSupportedException”.
2.3.4. Default Methods (Java 8)
Before java 8, it’s difficult to evolve interfaces because when you publish public API it
was very difficult to change something in interfaces like we discuss earlier
When we use abstract class to evolve our codes in the future , we have other problem is
Java doesn’t support multiple inheritance
So, the solution is to define other feature default method:
Main goal of introduce this feature is interface evolution that is we should be
able to add default methods after the interface has been released and should not
break client code. With binary compatibility
Interfaces with default implementation and a subclass can provide a more specific
implementation
Other name of default method: Defender or virtual extension methods
Syntax: to define default method in interface you need to use keyword “default” like this:
Default method is like instance method, you cannot access it by using interface name but
you can access by object name of class who implement this interface
Problem (diamond problem): when you have class which implement 2 interfaces A and
B and all theses interfaces have default method with same name So you have compiler
error
To resolve this problem you need to add implementation of this method in subclass
with same access modifier and same name
The method in the super class gets higher precedence over the default method interface.
That means when you have same method in super class and default in interface, the
subclass will take the implementation of super class
When you will call default method of super interface you can use super keyword
Default methods cannot override object’s methods
Conflict resolution strategies:
Classes win over interfaces
o Default methods cannot override object’s methods
Sub-interfaces win over super interfaces: when you have same default method in
2 interfaces and one extend the other, then version of sub-interface will win
Manual resolution
Super keyword:
Use parent.super when you need to invoke method in the super interface
Default method can be re-abstracted in a sub interface or in an abstract subclass. This is
done if a subtype thinks that a default implementation is not good enough and required its
own subtypes to provide better implementation
Can’t use final or synchronized modifiers with default methods
Benefits of default methods:
Interface evolution: default methods is really used by API designers
Default implementation that can overridden: subtypes can used for free or they
can override it
Eliminate utility classes:
o Example: list.sort() instead of Collections.sort(List) (list is interface)
Allow interface to stay as functional interface: is simply an interface with
exactly one abstract method (lambda expression work with only functional interface
with only one abstract method)
With java 8 we can add many default methods to functional interface with one
abstract method and lambda expression stay work
2.3.5. Static Methods in Interfaces
From java 8, we can have static methods in interfaces
Why Not static methods in pre-java 8 words?
Interfaces and static methods are stateless
One very good reason for this could be that interfaces are abstract specifications that
is define only contracts So including static methods seem to be against this print of
interfaces a static methods would include implementations and contract no
implementation
Interfaces can be associated with utility methods like this example
To recommodate such utility methods the convention of the patent is to provide a
separate companion utility class with the interface like java.util.Collections
Static utility methods can live with the interfaces itself and start off in a separate
companion class like nCopies methods
Default methods in an interface can invoke static methods in the same interface
Interface evolution will still holds if we add only static methods to an existing interface
Specific properties of static methods in interfaces:
Need to use static keyword to define static method in interface
Unlike static method in class, static methods in interfaces are not inherited
Static methods in interfaces can be invoked only via interface name (unlike of
static methods in class that we can invoked via reference object of class)