Recap of Java OOP
concepts
Procedural • Structured programming decomposes the
Programmi program’s functionality into various
procedures (functions), without much
ng vs concern about the data each procedure can
work with.
Object • Functions are free to operate and modify the
Oriented (usually global and unprotected) data.
• In Object Oriented Programming (OOP), data
Programmi and associated behavior forms a single unit,
which is referred to as a class.
ng
• The term encapsulation refers to combining
data and associated functions as a single
unit.
• For example, in a Circle class, radius and
center are defined as private fields. Now you
Encapsulati can add methods such as draw() and
fillColor() along with fields radius and center,
on since the fields and methods are closely
related to each other.
• All the data (fields) required for the methods
in the class are available inside the class
itself. In other words, the class encapsulates
its fields and methods together
• Access modifiers determine the level of visibility
for a Java entity (a class, method, or field).
• Access modifiers enable you to enforce effective
encapsulation. If all member variables of a class
can be accessed from anywhere, then there is no
Access point putting these variables in a class and no
purpose in encapsulating data and behavior
Modifiers together in a class.
• Java supports four types of access modifiers:
• Public
• Private
• Protected
• Default (no access modifier specified)
Access Modifiers
Demo
• The public access modifier is the most liberal
one. If a class or its members are declared as
public, they can be accessed from any other
class regardless of the package boundary.
Public
Access • A public method in a class is accessible to the
outside world only if the class is declared as
Modifier public. If the class does not specify any
access modifier (i.e., it has default access),
then the public method is accessible only
within the containing package.
• The private access modifier is the most
stringent access modifier. A private class
Private member cannot be accessed from outside
the class; only members of the same class
Access can access these private members.
• It’s comparable to a safe deposit box room
Modifier in a bank, which can only be accessed by a
set of authorized personnel and safe deposit
box owners.
• Protected and default access modifiers are quite
similar to each other. If a member method or field is
declared as protected or default, then the method or
field can be accessed within the package.
Protected • Note that there is no explicit keyword to provide
default access; in fact, when no access modifier is
and specified, the member has default access. Also, note
that default access is also known as package-
Default protected access.
• Protected and default accesses are comparable to the
Access situation in an office where a conference room is
accessible only to one department.
Modifiers • One significant difference between these two access
modifiers arises when we talk about a subclass
belonging to another package than its superclass. In
this case, protected members are accessible in the
subclass, whereas default members are not.
• Inheritance is a reusability mechanism in object-oriented
programming.
• With inheritance, the common properties of various
objects are exploited to form relationships with each
other.
• The abstract and common properties are provided in the
superclass, which is available to the more specialized
Inheritanc subclasses.
e
• For example, a color printer and a black-and-white
printer are kinds of a printer (single inheritance); an all-
in-one printer is a printer, scanner, and photocopier
(multiple inheritance).
• Consider a simple example used in earlier sections: class
Shape is a base class and Circle is a derived class. In other
words, a Circle is a Shape; similarly, a Square is a Shape.
Therefore, an inheritance relationship can be referred to
as an IS-A relationship.
Demo
Example –
Inheritance
• Individual abstractions offer certain functionalities
that need to be combined with other objects to
represent a bigger abstraction: a composite object
that is made up of other smaller objects.
Compositi • You need to make such composite objects to solve
real-life programming problems.
on vs • In such cases, the composite object shares HAS-A
relationships with the containing objects, and the
Inheritanc underlying concept is referred to as object
composition.
e • By way of analogy, a computer is a composite object
containing other objects such as CPU, memory, and a
hard disk.
• In other words, the computer object shares a HAS-A
relationship with other objects.
• A rule of thumb is to use HAS-A and IS-A phrases for
composition and inheritance, respectively. For instance,
• A computer HAS-A CPU.
• A circle IS-A shape.
Compositi • A circle HAS-A point.
• A laptop IS-A computer.
on vs • A vector IS-A list.
• This rule can be useful for identifying wrong
Inheritanc relationships.
• For instance, the relationship of car IS-A tire is
e (Contd) completely wrong, which means you cannot have an
inheritance relationship between the classes Car and
Tire.
• However, the car HAS-A tire (meaning car has one or
more tires) relationship is correct—you can compose a
Car object containing Tire objects.
Composition vs
Inheritance Demo
Constructor
Inheritance
Example
• The Greek roots of the term polymorphism
refer to the “several forms” of an entity.
Polymorphi • In the real world, every message you
communicate has a context. Depending on
sm the context, the meaning of the message
may change and so may the response to the
message.
• Polymorphism can be of two forms: dynamic
and static.
• When different forms of a single entity are
resolved during runtime (late binding), such
Types of polymorphism is called dynamic
polymorphism. Overriding is an example of
Polymorphi runtime polymorphism.
sm • When different forms of a single entity are
resolved at compile time (early binding),
such polymorphism is called static
polymorphism. Function overloading is an
example of static polymorphism.
• A base class reference can refer to a derived class object.
• You can invoke methods from the base class reference;
however, the actual method invocation depends on the
dynamic type of the object pointed to by the base class
reference.
Runtime • The type of the base class reference is known as the static type
of the object and the actual object pointed by the reference at
Polymorphi runtime is known as the dynamic type of the object.
• When the compiler sees the invocation of a method from a
sm base class reference and if the method is an overridable
method (a nonstatic and nonfinal method), the compiler defers
determining the exact method to be called to runtime (late
binding).
• At runtime, based on the actual dynamic type of the object, an
appropriate method is invoked. This mechanism is known as
dynamic method resolution or dynamic method invocation.
Runtime
Polymorhism Demo
• In OOP, the fundamental idea in inheritance is to
provide a default or common functionality in the
base class; the derived classes are expected to
provide more specific functionality.
Why do you • In this Shape base class and the Circle and Square
derived classes, the Shape provided the default
need to implementation of the area() method.
override • The derived classes of Circle and Square defined
their version of the area() method that overrides
methods? the base class area() method.
• So, depending on the type of the derived object
you create, from base class reference, calls to
area() method will be resolved to the correct
method.
• In Java, you can define multiple methods
with the same name, provided the argument
lists differ from each other.
Compile • In other words, if you provide different types
time of arguments, different numbers of
arguments, or both, then you can define
Polymorphi multiple methods with the same name.
sm • This feature is called method overloading.
• The compiler will resolve the call to a correct
method depending on the actual number
and/or types of the passed parameters.
Compile time
Polymorphism
Demo
Overload Resolution – What is the output?
• This process of the compiler trying to resolve
the method call from given overloaded
method definitions is called overload
resolution.
• For resolving a method call, it first looks for
Overload the exact match—the method definition with
exactly same number of parameters and
Resolution types of parameters.
• If it can’t find an exact match, it looks for the
closest match by using upcasts.
• Overload resolution fails (with a compiler
error) if there are no matches or ambiguous
matches.
What is the output?
What is the output?
• Overload resolution takes place entirely at compile
time (not at runtime).
• You cannot overload methods with the methods
differing in return types alone.
• For overload resolution to succeed, you need to
define methods such that the compiler finds one
Overload exact match. If the compiler finds no matches for your
call or if the matching is ambiguous, the overload
Resolution resolution fails and the compiler issues an error.
• The signature of a method is made up of the method
name, number of arguments, and types of arguments.
You can overload methods with same name but with
different signatures.
• Since return type and exception specification are not
part of the signature, you cannot overload methods
based on return type or exception specification alone.
Why should we override methods in the Object class?
• The toString() method is defined in the
Object class, which is inherited by all the
classes in Java.
• Here is the overview of the toString()
method as defined in the Object class: public
toString() String toString().
Method • The toString() method takes no arguments
and returns the String representation of the
object.
• The default implementation of this method
returns ClassName@hex version of the
object’s hashcode.
Modified Code
Overriding Issues
• Can the access modifier be changed to protected in the previous example where it was public?
Overriding Issues
What is the
output?
• Java provides covariant return types where you can give the
derived class of the return type in the overriding method.
• With the covariant return types feature introduced in Java 5,
you can provide the derived class of the return type in the
overriding method.
• In other words, you can change the definition of copy method
Covariant in Circle class as follows:
Return
Types
Overriding • The equals() method in the
Object class is an overridable
equals() method that takes the
Object type as an argument.
Method • It checks if the contents of
the current object and the
passed obj argument are
equal.
• If so, the equals() returns
true; otherwise it returns
false.
What is the output?
• @Override annotation was introduced in
Java 5.
• This annotation explicitly expresses to the
Java compiler the intention of the
programmer to use method overriding.
Override • In case the compiler is not satisfied with your
overridden method, it will issue a complaint,
Annotation which is a useful alarm for you.
• Also, the annotation makes the program
more understandable, since the @Override
annotation just before a method definition
helps you understand that you are overriding
a method.
What is the output?
• The main() method, where the main execution of the
program starts, is always declared static. Why
• You cannot override a static method provided in a
base class. Why?
• A static method cannot use the this keyword in its
body. Why?
Static • A static method cannot use the super keyword in its
body. Why?
Keyword • Since static methods cannot access instance variables
(nonstatic variables), they are most suited for utility
functions. That’s why there are many utility methods
in Java. For example, all methods in the
java.lang.Math library are static.
• Calling a static method is considered to be slightly
more efficient compared to calling an instance
method.
Graded
Assignment-1
Test Your Knowledge
Test Your Knowledge
Test Your
Knowled
ge
• Encapsulation: Combining data and the
functions operating on it as a single unit.
• You cannot access the private methods of
the base class in the derived class.
• You can access the protected method either
from a class in the same package (just like
Summary package private or default) as well as from a
derived class.
• You can also access a method with a default
access modifier if it is in the same package.
• You can access public methods of a class
from any other class.
• Inheritance: Creating hierarchical relationships between related
classes. Inheritance is also called an "IS-A" relationship.
• You use the super keyword to call base class methods.
• Inheritance implies IS-A and composition implies HAS-A relationship.
• Favor composition over inheritance.
• Polymorphism: Interpreting the same message (i.e., method call) with
different meanings depending on the context.
Summary • Resolving a method call based on the dynamic type of the object is
referred to as runtime polymorphism.
• Overloading is an example of static polymorphism (early binding)
while overriding is an example of dynamic polymorphism (late
binding).
• Method overloading: Creating methods with same name but different
types and/or numbers of parameters.
• You can have overloaded constructors. You can call a constructor of
the same class in another constructor using the this keyword.
• Overload resolution is the process by which the compiler
looks to resolve a call when overloaded definitions of a
method are available.
• In overriding, the name of the method, number of
arguments, types of arguments, and return type should
match exactly.
• In covariant return types, you can provide the derived
Summary class of the return type in the overriding method.
• There are two types of member variables: class variables
and instance variables.
• All variables that require an instance (object) of the class
to access them are known as instance variables.
• All variables that are shared among all instances and are
associated with a class rather than an object are referred
to as class variables (declared using the static keyword).