OOP_inJava_19T3
COMP2511
Object Oriented Programming (OOP)
in Java
Prepared by
Dr. Ashesh Mahidadia
OOP in Java
v Object Oriented Programming (OOP)
v Inheritance in OOP
v Introduction to Classes and Objects
v Subclasses and Inheritance
v Abstract Classes
v Single Inheritance versus Multiple Inheritance
v Interfaces
v Method Forwarding (Has-a relationship)
v Method Overriding (Polymorphism)
v Method Overloading
v Constructors
COMP2511: OOP in Java 2
Object Oriented Programming (OOP)
In procedural programming languages (like ‘C’), programming tends to be action-oriented,
whereas in Java – programming is object-oriented.
In procedural programming,
• groups of actions that perform some task are formed into functions and functions are grouped to
form programs.
In OOP,
• programmers concentrate on creating their own user-defined types called classes.
• each class contains data as well as the set of methods (procedures) that manipulate the data.
• an instance of a user-defined type (i.e. a class) is called an object.
• OOP encapsulates data (attributes) and methods (behaviours) into objects, the data and methods
of an object are intimately tied together.
• Objects have the property of information hiding.
COMP2511: OOP in Java 3
Inheritance in Object Oriented Programming (OOP)
v Inheritance is a form of software reusability in which new classes are created from the
existing classes by absorbing their attributes and behaviours.
v Instead of defining completely (separate) new class, the programmer can designate
that the new class is to inherit attributes and behaviours of the existing class (called
superclass). The new class is referred to as subclass.
v Programmer can add more attributes and behaviours to the subclass, hence,
normally subclasses have more features than their super classes.
COMP2511: OOP in Java 4
Inheritance in Object Oriented Programming (OOP)
Inheritance relationships form tree-like hierarchical structures. For example,
COMP2511: OOP in Java 5
“Is-a” – Inheritance relationship
v In an “is-a” relationship, an object of a subclass may also be treated as an object of the
superclass.
v For example, UndergraduateStudent can be treated as Student too.
v You should use inheritance to model “is-a” relationship.
Very Important:
v Don’t use inheritance unless all or most inherited attributes and methods make sense.
v For example, mathematically a circle is-a (an) oval, however you should not inherit a class circle
from a class oval. A class oval can have one method to set width and another to set height.
COMP2511: OOP in Java 6
“Has-a” – Association relationship
v In a “has-a” relationship, a class object has an object of another class to store its state or do its
work, i.e. it “has-a” reference to that other object.
v For example, a Rectangle Is-NOT-a Line.
However, we may use a Line to draw a Rectangle.
v The “has-a” relationship is quite different from an “is-a” relationship.
v “Has-a” relationships are examples of creating new classes by composition of existing classes (as
oppose to extending classes).
Very Important:
v Getting “Is-a” versus “Has-a” relationships correct is both subtle and potentially critical. You
should consider all possible future usages of the classes before finalising the hierarchy.
v It is possible that obvious solutions may not work for some applications.
COMP2511: OOP in Java 7
Designing a Class
• Think carefully about the functionality (methods) a class should offer.
• Always try to keep data private (local).
• Consider different ways an object may be created.
• Creating an object may require different actions such as initializations.
• Always initialize data.
• If the object is no longer in use, free up all the associated resources.
• Break up classes with too many responsibilities.
• In OO, classes are often closely related. “Factor out” common attributes and behaviours
and place these in a class. Then use suitable relationships between classes (for example,
“is-a” or “has-a”).
COMP2511: OOP in Java 8
Introduction to Classes and Objects
v A class is a collection of data and methods (procedures) that operate on that data.
v For example,
a circle can be described by the x, y position of its centre and by its radius.
v We can define some useful methods (procedures) for circles,
compute circumference, compute area, check whether pointes are inside the circle,
etc.
v By defining the Circle class (as below), we can create a new data type.
COMP2511: OOP in Java 9
The class Circle
v For simplicity, the methods for getter and
setters are not shown in the code.
COMP2511: OOP in Java 10
Objects are Instances of a class
In Java, objects are created by instantiating a class.
For example,
Circle c ;
c = new Circle ( ) ;
OR
Circle c = new Circle ( ) ;
COMP2511: OOP in Java 11
Accessing Object Data
We can access data fields of an object.
For example,
Circle c = new Circle ( ) ;
// Initialize our circle to have centre (2, 5)
// and radius 1.
// Assuming, x, y and r are not private
c.x = 2;
c.y = 5;
c.r = 1;
COMP2511: OOP in Java 12
Using Object Methods
To access the methods of an object, we can use the same syntax as accessing the data of
an object:
Circle c = new Circle ( ) ;
double a;
c.r = 2; // assuming r is not private
a = c.area( );
//Note that its not : a = area(c) ;
COMP2511: OOP in Java 13
Subclasses and Inheritance:
First Approach
We want to implement GraphicalCircle.
This can be achieved in at least 3 different ways.
First Approach:
v In this approach we are creating the
new separate class for GraphicalCircle and
re-writing the code already available in the class
Circle.
v For example, we re-write the methods area and
circumference.
v Hence, this approach is NOT elegant, in fact its
the worst possible solution.
Note again, its the worst possible solution!
COMP2511: OOP in Java 14
Subclasses and Inheritance:
Second Approach
v We want to implement GraphicalCircle so
that it can make use of the code in the class
Circle.
v This approach uses “has-a” relationship.
v That means, a GraphicalCircle has a
(mathematical) Circle.
v It uses methods from the class Circle (area
and circumference) to define some of the
new methods.
v This technique is also known as method
forwarding.
COMP2511: OOP in Java 15
Subclasses and Inheritance:
Third Approach – Extending a Class
v We can say that GraphicalCircle is-a Circle.
v Hence, we can define GraphicalCircle as an
extension, or subclass of Circle.
v The subclass GraphicalCircle inherits all the
variables and methods of its superclass Circle.
COMP2511: OOP in Java 16
Subclasses and Inheritance: Example
We can assign an instance of GraphicCircle to a Circle variable. For example,
GraphicCircle gc = new GraphicCircle();
…
double area = gc.area();
…
Circle c = gc;
// we cannot call draw method for “c”.
Important:
v Considering the variable “c” is of type Circle,
v we can only access attributes and methods available in the class Circle.
v we cannot call drawmethod for “c”.
COMP2511: OOP in Java 17
Super classes, Objects, and the Class Hierarchy
v Every class has a superclass.
v If we don’t define the superclass, by default, the superclass is the class Object.
Object Class :
v Its the only class that does not have a superclass.
v The methods defined by Object can be called by any Java object (instance).
v Often we need to override the following methods:
v toString()
v equals()
v hasCode()
COMP2511: OOP in Java 18
Abstract Classes
Using abstract classes,
v we can declare classes that define only part of an implementation,
v leaving extended classes to provide specific implementation of some or all the
methods.
The benefit of an abstract class
v is that methods may be declared such that the programmer knows the interface
definition of an object,
v however, methods can be implemented differently in different subclasses of the
abstract class.
COMP2511: OOP in Java 19
Abstract Classes
Some rules about abstract classes:
v An abstract class is a class that is declared abstract.
v If a class includes abstract methods, then the class itself must be declared abstract.
v An abstract class cannot be instantiated.
v A subclass of an abstract class can be instantiated if it overrides each of the abstract
methods of its superclass and provides an implementation for all of them.
v If a subclass of an abstract class does not implement all the abstract methods it
inherits, that subclass is itself abstract.
COMP2511: OOP in Java 20
Abstract Class: Example
COMP2511: OOP in Java 21
Abstract Class: Example
COMP2511: OOP in Java 22
Abstract Class: Example
COMP2511: OOP in Java 23
We can now write code like this:
Some points to note:
v As Shape is an abstract class, we cannot
instantiate it.
v Instantiations of Circle and Rectangle can be
assigned to variables of Shape.
No cast is necessary
v In other words, subclasses of Shape can be
assigned to elements of an array of Shape.
No cast is necessary.
v We can invoke area() and circumference()
methods for Shape objects.
Single Inheritance versus Multiple Inheritance
• In Java, a new class can extend exactly one superclass – a
model known as single inheritance.
• Some object-oriented languages employ multiple
inheritance, where a new class can have two or more super
classes.
• In multiple inheritance, problems arise when a superclass’s
behaviour is inherited in two/multiple ways.
• Single inheritance precludes some useful and correct
designs.
• In Java, interface in the class hierarchy can be used to add
multiple inheritance, more discussions on this later.
COMP2511: OOP in Java 24
Diamond inheritance
problem
Interfaces in Java
v Interfaces are like abstract classes, but with few important differences.
v All the methods defined within an interface are implicitly abstract. (We don’t need to
use abstract keyword, however, to improve clarity one can use abstract keyword).
v Variables declared in an interface must be static and final, that means,
they must be constants.
v Just like a class extends its superclass, it also can optionally implements an interface.
v In order to implement an interface, a class must first declare the interface in an
implements clause, and then it must provide an implementation for all of the abstract
methods of the interface.
v A class can “implements” more than one interfaces.
v More discussions on “interfaces” later in the course.
COMP2511: OOP in Java 25
Interfaces in Java: Example
COMP2511: OOP in Java 26
Using Interfaces: Example
v When a class implements an
interface, instance of that class can
also be assigned to variables of the
interface type.
COMP2511: OOP in Java 27
Implementing Multiple Interfaces
COMP2511: OOP in Java
28
A class can implements more than one interfaces. For example,
Extending Interfaces
v Interfaces can have sub-interfaces, just like classes can have subclasses.
v A sub-interface inherits all the abstract methods and constants of its super-interface,
and may define new abstract methods and constants.
v Interfaces can extend more than one interface at a time. For example,
COMP2511: OOP in Java 29
Method Forwarding
v Suppose class C extends class A, and also implements interface X.
v As all the methods defined in interface X are abstract, class C needs to implement all
these methods.
v However, there are three implementations of X (in P,Q,R).
v In class C, we may want to use one of these implementations, that means, we may
want to use some or all methods implemented in P, Q or R.
v Say, we want to use methods implemented in P. We can do this by creating an object
of type class P in class C, and through this object access all the methods implemented
in P.
v Note that, in class C, we do need to provide required stubs for all the methods in the
interface X. In the body of the methods we may simply call methods of class P via the
object of class P.
v This approach is also known as method forwarding.
COMP2511: OOP in Java 30
Methods Overriding (Polymorphism)
v When a class defines a method using the same name, return type,
and by the number, type, and position of its arguments as a method in its superclass,
the method in the class overrides the method in the superclass.
v If a method is invoked for an object of the class, it’s the new definition of the method
that is called, and not the superclass’s old definition.
Polymorphism
• An object’s ability to decide what method to apply to itself, depending on where
it is in the inheritance hierarchy, is usually called polymorphism.
COMP2511: OOP in Java 31
Methods Overriding: Example
In the example below,
v if p is an instance of class B,
p.f() refers to f() in class B.
v However, if p is an instance of class A,
p.f() refers to f() in class A.
The example also shows how to refer to the overridden method using super keyword.
COMP2511: OOP in Java 32
Methods Overriding: Example
Suppose class C is a subclass of class B, and class B is a subclass of class A.
Class A and class C both define method f().
From class C, we can refer to the overridden method by,
super.f()
This is because class B inherits method f() from class A.
However,
v if all the three classes define f(), then
calling super.f() in class C invokes class B’s definition of the method.
v Importantly, in this case, there is no way to invoke A.f() from within class C.
v Note that super.super.f() is NOT legal Java syntax.
COMP2511: OOP in Java 33
Method Overloading
Defining methods with the same name and different argument or return types is called
method overloading.
In Java,
v a method is distinguished by its method signature – its name, return type, and by the
number, type, and position of its arguments
For example,
double add(int, int)
double add(int, double)
double add(float, int)
double add(int, int, int)
double add(int, double, int)
COMP2511: OOP in Java 34
Data Hiding and Encapsulation
We can hide the data within the class and make it available only through the methods.
This can help in maintaining the consistency of the data for an object, that means the state
of an object.
Visibility Modifiers
Java provides five access modifiers (for variables/methods/classes),
v public – visible to the world
v private – visible to the class only
v protected – visible to the package and all subclasses
v No modifier (default) – visible to the package
COMP2511: OOP in Java 35
Constructors
v Good practice to define the required constructors for all classes.
v If a constructor is not defined in a class,
o no-argument constructor is implicitly inserted.
o this no-argument constructor invokes the superclass’s no-argument constructor.
o if the parent class (superclass) doesn’t have a visible constructor with no-argument,
it results in a compilation error.
v If the first statement in a constructor is not a call to super() or this(),
a call to super () is implicitly inserted.
v If a constructor is defined with one or more arguments,
no-argument constructor is not inserted in that class.
v A class can have multiple constructors, with different signatures.
v The word “this” can be used to call another constructor in the same class.
COMP2511: OOP in Java 36
Diamond Inheritance Problem: A Possible Solution
COMP2511: OOP in Java 37
Some References to Java Tutorials
v https://docs.oracle.com/javase/tutorial/
v https://www.w3schools.com/java/default.asp
v https://www.tutorialspoint.com/java/index.htm
COMP2511: OOP in Java 38