Part 2 - Java programming intermediate
Part 2 - Java programming intermediate
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).
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
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
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
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:
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:
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
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
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)
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
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
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
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
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
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
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
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:
Implementing interface:
By using keyword implements
Implement multiple interfaces: you can implement many interfaces for same class
like this
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
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
Principle reason for using interfaces is that java doesn’t support multiple
inheritances
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
If you not implement the marker interface Cloneable and try to clone object by
Object class clone method then compiler will throw “CloneNotSupportedException”.
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
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)