0% found this document useful (0 votes)
0 views85 pages

Object Oriented Programming

This document provides an overview of Object-Oriented Programming (OOP) concepts using Java, highlighting key principles such as encapsulation, inheritance, polymorphism, and abstraction. It explains the advantages of OOP over procedural programming, including ease of software design, maintenance, and reusability. Additionally, it covers class and object definitions, instance creation, and the importance of encapsulation in managing data accessibility.

Uploaded by

itstd.7698
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views85 pages

Object Oriented Programming

This document provides an overview of Object-Oriented Programming (OOP) concepts using Java, highlighting key principles such as encapsulation, inheritance, polymorphism, and abstraction. It explains the advantages of OOP over procedural programming, including ease of software design, maintenance, and reusability. Additionally, it covers class and object definitions, instance creation, and the importance of encapsulation in managing data accessibility.

Uploaded by

itstd.7698
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Basic Concepts in Object Oriented Programming

using Java

Notes for the Computer Science Module


Object Oriented Programming

Computer Science Department


Faculty of Information Technology, University of Benghazi

Instructor: Saria Eltalhi

Instructor: Saria Eltalhi - Faculty of Information Technology Page 1


Java Quick Reference

Text book: [1]

Instructor: Saria Eltalhi - Faculty of Information Technology Page 2


Java language
The Java language is easier to understand (and write) than languages such
as C and C++. The biggest reason for this is that Java doesn't use pointers.
Although it surprises some people, pointers aren't necessary for the creation
of complex data structures and algorithms. In fact, eliminating pointers
makes such code not only easier to write and to understand, but more secure
and less prone to errors as well.

Java is a modern object-oriented language, which means we can use an


object-oriented approach for the programming examples. This is important,
because object-oriented programming (OOP) offers compelling advantages
over the old-fashioned procedural approach, and is quickly supplanting it for
serious program development.

Java is an Object-Oriented Language. As a language that has the Object-Oriented


feature, Java supports the following fundamental concepts:

 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

Problems with Procedural Languages

OOP was invented because procedural languages, such as C, Pascal, and


BASIC, were found to be inadequate for large and complex programs. Why
was this?
The problems have to do with the overall organization of the program.
Procedural
programs are organized by dividing the code into functions (called procedures
or
subroutines in some languages). Groups of functions could form larger units
called
modules or files.

Crude Organizational Units

One difficulty with this kind of function-based organization was that it


focused on
functions at the expense of data. There weren't many options when it came
to data. To simplify slightly, data could be local to a particular function or it
could be global accessible to all functions. There was no way (at least not a
flexible way) to specify that some functions could access a variable and others
couldn't.
This caused problems when several functions needed to access the same data.
To be available to more than one function, such variables had to be global,
but global data could be accessed inadvertently by any function in the

Instructor: Saria Eltalhi - Faculty of Information Technology Page 3


program. This lead to frequent programming errors. What was needed was a
way to fine-tune data accessibility, allowing variables to be available to
functions with a need to access it, but hiding it from others

1. Benefits of OOP
The procedural-oriented languages focus on procedures, with function as the
basic unit. You need to first figure out all the functions and then think about
how to represent data.
The object-oriented languages focus on components that the user perceives,
with objects as the basic unit. You figure out all the objects by putting all the
data and operations that describe the user's interaction with the data.

Object-Oriented technology has many benefits:

 Ease in software design as you could think in the problem space rather
than the machine's bits and bytes. You are dealing with high-level
concepts and abstractions. Ease in design leads to more productive
software development.

 Ease in software maintenance: object-oriented software are easier to


understand, therefore easier to test, debug, and maintain.

 Reusable software: you don't need to keep re-inventing the wheels and
re-write the same functions for different situations. The fastest and
safest way of developing a new application is to reuse existing codes -
fully tested and proven codes.

2. OOP in Java
 Encapsulation

Encapsulation simply means binding object state(fields) and


behaviour(methods) together as a single unit. If you are creating class, you
are doing encapsulation

The whole idea behind encapsulation is to hide the implementation details


from users. If a data member is private it means it can only be accessed within
the same class. No outside class can access private data member (variable) of
other class
In encapsulation, the variables of a class will be hidden from other classes, and can
be accessed only through the methods of their current class. Therefore, it is also
known as data hiding.
To achieve encapsulation in Java −
 Declare the variables of a class as private.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 4


 Provide public setter and getter methods to modify and view the variables
values.

Benefits of Encapsulation
 The fields of a class can be made read-only or write-only.

 A class can have total control over what is stored in its fields

Advantages of Encapsulation in Java

 Encapsulation is binding the data with its related functionalities. Here


functionalities mean "methods" and data means "variables"
 So we keep variable and methods in one place. That place is "class."
Class is the base for encapsulation.
 With Java Encapsulation, you can hide (restrict access) to critical data
members in your code, which improves security
 As we discussed earlier, if a data member is declared "private", then it
can only be accessed within the same class. No outside class can access
data member (variable) of other class.
 However, if you need to access these variables, you have to use public

"getter" and "setter" methods.

Class & Instances


The two most important concepts in object-oriented programming are the
class and the object.
In Java, a class is a definition of objects of the same kind. In other words,
a class is a blueprint, template, or prototype that defines and describes
the static attributes and dynamic behaviors common to all objects of the
same kind.
An instance is a realization of a particular item of a class. In other words, an
instance is an instantiation of a class. All the instances of a class have similar
properties
An object is comprised of data and operations that manipulate these data.
For example, a Student object may consist of data such as name, gender,
birth date, home address, phone number, and age and operations for
assigning and changing these data values, we will use standard notation
called UML, which stands for Unified Modeling Language to represent class
and object.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 5


A Class is a 3-Compartment Box encapsulating Data and Operations

In the UML, each class is modeled in a class diagram as a rectangle with three
compartments, as illustrated:

1. Name (or identity): identifies the name of the class centered horizontally in
boldface
2. Variables (or attribute, state, field): contains the class’s attributes, which
correspond to instance variables.
3. Methods (or behaviors, function, operation): contains the dynamic
behaviors of the class, , which correspond to methods in Java

In other words, a class encapsulates the static attributes (data) and dynamic
behaviors (operations that operate on the data) in a box.
The illustration of class templates and objects in Figure 1 can be
standardized using UML (Unified Modeling Language) notations

Figure 1:

The followings figure shows a few examples of classes:

Figure 2: UML Class Diagram

Student

Figure 3: Graphical representation of an object

Instructor: Saria Eltalhi - Faculty of Information Technology Page 6


class :
A class is a kind of mold or template that dictates what objects can and
cannot do

Fields, properties, attributes

The global (declared outside of any method) variables of a class are its fields,
properties, or attributes. All of these are synonyms. They make up the state
of the class (if static) or objects (if dynamic).

Methods

The functions and procedures in a class are its methods. They implement the
services that the class or objects provide.

Constructors

The special subprograms that are called when an object is created, are called
constructors. Their main purpose is to initialize the state of new dynamic
objects.

Members of a class
The members of a class are its fields, methods, constructors, and anything
else declared at the top level in the class.

Learn Encapsulation with an Example


Consider the following bank account class with deposit and show balance
methods

public class Account {


private int account_number;
private int account_balance;

Instructor: Saria Eltalhi - Faculty of Information Technology Page 7


public void show Data() {
//code to show data
}

public void deposit(int a) {


if (a < 0) {
//show error
} else
account_balance = account_balance + a;
}
}

Now, he tries to deposit amount -100 into your account

The keyword public is an access modifier. For now, we’ll simply declare every
class public. Every class declaration contains keyword class followed
immediately by the class’s name. Every class’s body is enclosed in a pair of
left and right braces

Instances of a class (Object): Object Creation

An object is called an instance of a class. An object is an instance of exactly


one class. The object will include all of the dynamic fields and methods
defined in the class
An object has a unique identity, state, and behavior.
 The state of an object (also known as its properties or attributes) is
represented by data fields with their current values. A circle object, for
example, has a data field radius, which is the property that
characterizes a circle
 The behavior of an object (also known as its actions) is defined by
methods. To invoke a method on an object is to ask the object to
perform an action. For example, you may define a method named
getArea() for circle objects. A circle object may invoke getArea() to return
its area

An object is an instance of a class. You can create many instances of a class.


Creating an instance is referred to as instantiation.
In Java, a class is a type, similar to the built-in types such as int and boolean.
So, a class name can be used to specify the type of a variable in a declaration
statement, the type of a formal parameter, or the return type of a function.
For example, a program could define a variable named std of type Student with
the statement

Student std;

Instructor: Saria Eltalhi - Faculty of Information Technology Page 8


However, declaring a variable does not create an object! This is an important
point, which is related to this Very Important Fact:

In Java, no variable can ever hold an object.


A variable can only hold a reference to an object.

You should think of objects as floating around independently in the


computer’s memory. In fact, there is a special portion of memory called the
heap where objects live. Instead of holding an object itself, a variable holds
the information necessary to find the object in memory. This information is
called a reference or pointer to the object. In effect, a reference to an object
is the address of the memory location where the object is stored. When you use
a variable of object type, the computer uses the reference in the variable to
find the actual object.

We create an object by invoking the new operator. The syntax for new is [20]

<object name> = new <class name> ( <arguments> ) ;

Next figure shows the distinction between object declaration and creation
Now, consider the following object declaration and two statements of object
creation:
Customer customer;

customer = new Customer( );

customer = new Customer( );

We can write, for example,


Student john = new Student();
instead of
Student john;
john = new Student();

Instructor: Saria Eltalhi - Faculty of Information Technology Page 9


Message passing
When you read about object oriented programming, you see the term message
passing.
It occurs when one object sends information to, or requests a service of
another. This is done by one object calling another’s method. The first object
sends information as the method’s actual parameters, and the second object
can send information back as a function’s result (or by calling back to one of
the first object’s methods).

Messages and
Methods

UML class diagrams

Figure 4: Classes and objects can be represented using UML notations

Instructor: Saria Eltalhi - Faculty of Information Technology Page 10


Class Definition
In Java, we use the keyword class to define a class. For examples:

public class Circle { // class name

double radius; // variables


String color;

double getRadius() {...} // methods


double getArea() {...}
}

The syntax for class definition in Java is:


[Access_Control_Modifier] class ClassName {
// class body contains definition of variables and methods ...}

Creating Instances of a Class

To create an instance of a class, you have to:


1. Declare an instance identifier (instance name) of a particular class.
2. Construct the instance (i.e., allocate storage for the instance and
initialize the instance) using the "new" operator.

For examples, suppose that we have a class called Circle, we can create instances of Circle as
follows:

// Declare 3 instances of the class Circle, c1, c2, and c3


Circle c1, c2, c3;
// Allocate and construct the instances via new operator
c1 = new Circle();
c2 = new Circle(2.0);
c3 = new Circle(3.0, "red");
// You can declare and construct in the same statement
Circle c4 = new Circle();

Exercise: You have two classes Patient and Appointment


Write java code to implemented these classes

Instructor: Saria Eltalhi - Faculty of Information Technology Page 11


Classes and Objects (from Alan)
Note
At times, you may want to store derived attributes, which are attributes that
can be calculated or derived; these special attributes are denoted by placing
a slash (/) before the attribute’s name

the person class contains a derived attribute called


/age, which can be derived by subtracting the
patient’s birth date from the current date.

Age= current date - birth date

 Java naming conventions


Start classes with uppercase letters
– Constructors (discussed later in this section) must exactly match
class name, so they also start with uppercase letters

public class MyClass { ... }

 Format of class definitions


Start other things with lowercase letters
– Instance variables, local variables, methods, parameters to methods

public class MyClass


{
public String firstName, lastName;
public String fullName() {

Instructor: Saria Eltalhi - Faculty of Information Technology Page 12


String name = firstName + " " + lastName;
return(name);
}
}

 objects and References

 Once a class is defined, you can declare variables (object reference) of


that type
Ship s1, s2;
Point start;
Color blue;

 Object references are initially null


– The null value is a distinct type in Java and is not equal to zero

 The new operator is required to explicitly create the object that is


referenced
ClassName variableName = new ClassName();

Instructor: Saria Eltalhi - Faculty of Information Technology Page 13


Illustrative Diagrams

Illustrative diagrams are used to explain all key concepts of programming


such as the difference between object declaration and creation, the distinction
between the primitive data type and the reference data type, the call-by-value
parameter passing, inheritance, and many others.

Member Variables (instance variables)


A member variable has a name (or identifier) and a type; and holds a value of
that particular type. A member variable can also be an instance of a certain
class
For example,

private double radius;


public int length = 1, width = 1;

– Data that is stored inside an object. “Instance variables” can also be called
“data
members” or “fields.
A class normally consists of one or more methods that manipulate the
attributes that belong to a particular object of the class. Attributes are

Instructor: Saria Eltalhi - Faculty of Information Technology Page 14


represented as variables in a class declaration. Such variables are called fields
and are declared inside a class declaration but outside the bodies of the
class’s method declarations. When each object of a class maintains its own
copy of an attribute, the field that represents the attribute is also known as
an instance variable—each object (instance) of the class has a separate
instance of the variable in memory.

Member Methods
Methods: Communicating with Objects

Definition
– Functions that are defined inside a class. “Methods” can also be called
“member functions
A method:
1. receives parameters from the caller,
2. performs the operations defined in the method body, and
3. returns a piece of result (or void) to the caller.

Syntax:
The syntax for method declaration in Java is as follows:

[Access_Modifier] returnType methodName ([argumentList]) {


// method body or implementation
......
}

For examples:
public double getArea() {
return radius*radius*Math.PI;
}

Methods and parameters are the primary mechanisms for passing


information into and out of an object

The method declaration begins with keyword public to indicate that the
method is “available to the public”—it can be called from methods of other
classes. Next is the method’s return type, which specifies the type of data the
method returns to its caller after performing its task. The return type void
indicates that this method will perform a task but will not return (i.e., give
back) any information to its calling method.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 15


Variables declared in the body of a particular method are known as local
variables and can be used only in that method. When that method terminates,
the values of its local variables are lost.

Method names begin with a lowercase first letter and subsequent words in the
name begin with a capital letter. The parentheses after the method name
indicate that this is a method.
Empty parentheses indicate that this method does not require additional
information to perform its task. The body of a method contains one or more
statements that perform the method’s task.

public void displayMessage()


{
System.out.println( "Welcome to the Grade Book!" );
} // end method displayMessage

Instructor: Saria Eltalhi - Faculty of Information Technology Page 16


Constructors

Defining Constructors
Initializing Objects with Constructors

A Java class uses variables to define data fields and methods to define actions.
Additionally, a class provides methods of a special type, known as
constructors, which are invoked to create a new object. A constructor can
perform any action, but constructors are designed to perform initializing
actions, such as initializing the data fields of objects.

The general syntax for declaring a constructor in Java is as follows:

modifiers name (type0 parameter0 , . . . , typen− 1 parametern− 1)


{ // constructor body . . .}

Rules or properties of a constructor

1. Constructor will be called automatically when the object is created.

2. Constructor name must be similar to name of the class.

3. Constructor should not return any value even void also. Because
basic aim is to place the value in the object. (if we write the return
type for the constructor then that constructor will be treated as
ordinary method).

4. Constructor definitions should not be static. Because constructors


will be called each and every time, whenever an object is creating.

5. Constructor should not be private provided an object of one class is


created in another class (Constructor can be private provided an
object of one class created in the same class).

6. Constructors will not be inherited from one class to another class


(Because every class constructor is create for initializing its own
data members).

7. The access specifier of the constructor may or may not be private.


i. If the access specifier of the constructor is private then an
object of corresponding class can be created in the context of
the same class but not in the context of some other classes.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 17


ii. If the access specifier of the constructor is not private then an
object of corresponding class can be created both in the same
class context and in other class context.

Constructors. Constructors cannot return a value. Therefore, no


return type should be declared when the constructor is defined.

Types of java constructors

There are two types of constructors:


1. Default constructor (no- argument constructor)
2. Parameterized constructor

Constructors are defined in a very similar way as other methods of a class,


but there are a few important distinctions:

1. Constructors cannot be static, abstract, or final, so the only modifiers


that are allowed are those that affect visibility (i.e., public, protected,
private, or the default package-level visibility).

2. The name of the constructor must be identical to the name of the class
it constructs. For example, when defining the Counter class, a
constructor must be named Counter as well.

3. We don’t specify a return type for a constructor (not even void). Nor
does the body of a constructor explicitly return anything. When a user
of a class creates an instance using a syntax such as

Counter d = new Counter(5);

the new operator is responsible for returning a reference to the new instance
to the caller; the responsibility of the constructor method is only to initialize
the state of the new instance.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 18


A class can have many constructors, but each must have a different
signature, that is, each must be distinguished by the type and number of the
parameters it takes.

Default Constructors
If no constructors are explicitly defined, Java provides an implicit default
constructor for the class, having zero arguments and leaving all instance
variables initialized to their default values. However, if a class defines one or
more nondefault constructors, no default constructor will be provided

class Circle
{
/** The radius of this circle */ Data field
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
/** Construct a circle object */ Constructors
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */ Method
double getArea() {
return radius * radius * Math.PI;
}
}

The default constructor takes no parameters

Like regular methods, constructors can be overloaded (i.e., multiple


constructors can have the same name but different signatures), making it
easy to construct objects with different initial data values

A class may be defined without constructors. In this case, a no-arg


constructor with an empty body is implicitly defined in the class. This
constructor, called a default constructor, is provided automatically only if no
constructors are explicitly defined in the class [4]

If there is no constructor in a class, compiler automatically creates a


default constructor

Instructor: Saria Eltalhi - Faculty of Information Technology Page 19


How Constructor eliminate default values?

Constructor are mainly used for eliminate default values by user defined values,
whenever we create an object of any class then its allocate memory for all the data
members and initialize there default values. To eliminate these default values by
user defined values we use constructor

This Keyword
The “this” Variable
1. The this variable
– The this object reference can be used inside any non-static method to
refer to the current object

2. The common uses of the “this” reference are:


 this can be used to refer current class instance variable. (To resolve name
conflicts)
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 20


Why use this keyword in java?

The main purpose of using this keyword is to differentiate the formal parameter and
data members of class, whenever the formal parameter and data members of the class
are similar then jvm get ambiguity (no clarity between formal parameter and member
of the class)

"this" keyword is used for two purpose, they are

 It always points to current class object.


 Whenever the formal parameter and data member of the class are similar and
JVM gets an ambiguity (no clarity between formal parameter and data
members of the class).

Using this with a Field

public class Point {


public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

• It
is only necessary to say this.fieldName when you have a local variable
and a field with the same name; otherwise just use fieldName with no “this”

this ()

which can be used to call one constructor within the another constructor
without creation of objects multiple time for the same class.

Syntax

this(); // call no parametrized or default constructor


this(value1,value2,.....) //call parametrize constructor

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor
in the same class. Doing so is called an explicit constructor invocation. Here's

Instructor: Saria Eltalhi - Faculty of Information Technology Page 21


another Rectangle class, with a different implementation from the one in
the Objects section.

public class Rectangle {


private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 1, 1); }

public Rectangle(int width, int height) {


this(0, 0, width, height); }

public Rectangle(int x, int y, int width, int height) {


this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}

this keyword used to invoke current class method (implicitly)

By using this keyword you can invoke the method of the current class. If you do
not use this keyword, compiler automatically adds this keyword at time of
invoking of the method.

class Student
{
void show() { System.out.println("You got A+");
}
void marks() { this.show(); } //no need to use this here because compiler does it.

void display() { show(); } //compiler act marks() as this.marks()

public static void main(String args[])


{
Student s = new Student();
s.display();
}
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 22


Modifier Types
Modifiers are keywords that you add to those definitions to change their meanings. The Java
language has a wide variety of modifiers, including the following:

 Java Access Modifiers


 Non Access Modifiers

To use a modifier, you include its keyword in the definition of a class, method, or variable

 Default Access Modifier - No Keyword


Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc.

A variable or method declared without any access control modifier is available to any other class
in the same package. The fields in an interface are implicitly public static final and the methods
in an interface are by default public

Access Modifiers (Visibility Modifiers)

A visibility modifier specifies how data fields and methods in a class can be
accessed from outside the class. There is no restriction on accessing data
fields and methods from inside the class.

 Public Access Modifier - Public


You can use the public visibility modifier for classes, methods, and data fields
to denote that they can be accessed from any other classes. If no visibility
modifier is used, then by default the classes, methods, and data fields are
accessible by any class in the same package. This is known as package-
private or package-access

In most cases, the constructor should be public. However, if you want to


prohibit the user from creating an instance of a class, use a private
constructor

 Private Access Modifier - Private


Methods, variables, and constructors that are declared private can only be
accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and
interfaces cannot be private
Variables that are declared private can be accessed outside the class, if
public getter methods are present in the class

Instructor: Saria Eltalhi - Faculty of Information Technology Page 23


You can provide a get method or a set method to enable clients to see or
modify the data. Colloquially, a get method is referred to as a getter (or
accessor), and a set method as a setter (or mutator).[4]

 set Methods and get Methods


Variables or methods declared with access modifier private are accessible
only to methods of the class in which they’re declared

Declaring instance variables with access modifier private is known as data


hiding or
information hiding
In our next example, class GradeBook maintains the course name as an
instance variable and three methods—setCourseName, getCourseName and
displayMessage. Method setCourseName stores a course name in a
GradeBook.
Method getCourseName obtains a GradeBook’s course name. Method
displayMessage which now specifies no parameters, still displays a welcome
message that includes the course name; as you’ll see, the method now obtains
the course name by calling a method in the same class—getCourseName
// GradeBook class that contains a courseName instance variable
// and methods to set and get its value.
public class GradeBook
{
private String courseName; // course name for this GradeBook
// method to set the course name

public void setCourseName( String name )

Instructor: Saria Eltalhi - Faculty of Information Technology Page 24


{
courseName = name; // store the course name
} // end method setCourseName

// method to retrieve the course name


public String getCourseName()
{
return courseName;
} // end method getCourseName

// display a welcome message to the GradeBook user


public void displayMessage
{
// calls getCourseName to get the name of the course this GradeBook
represents
System.out.printf( "Welcome to the grade book for\n%s!\n",
getCourseName() );
} // end method displayMessage
} // end class GradeBook
When a program creates (instantiates) an object of class GradeBook, variable
courseName is encapsulated (hidden) in the object and can be accessed only
by methods of the object’s class. This prevents courseName from being
modified accidentally by a class in another part of the program. In class
GradeBook,methods setCourseName and getCourseName manipulate the
instance variable courseName

 UML Class Diagram with an Instance Variable and set and get Methods

The plus sign (+) before each operation name indicates that the operation is
public.
The minus sign (-) before each Instance variable indicates that the variable
is private.

 Protected Access Modifier - Protected

Instructor: Saria Eltalhi - Faculty of Information Technology Page 25


Variables, methods, and constructors, which are declared protected in a
superclass can be accessed only by the subclasses in other package or any
class within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces.


Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.

 Passing Information to an Object

One convention of object-oriented programming is to provide public


methods to set and get the values of some of its private instance variables.
Methods that set or modify an object’s instance variables are called mutator
methods. Methods that get or retrieve the value of an instance variable are
called accessor methods

Accessor and Mutator Methods. An accessor method is a public method


used to get the value of an object’s instance variable. Such methods are
often named getVarName() where VarName is the name of the variable
that’s being accessed. A mutator method is a public method used to modify
the value of one or more instance variables. The special type of mutator
method that sets or assigns a variable a specified value is often called
setVarName().

It is up to the designer of the class to determine which private variables


require accessor and mutator methods. If you were designing a BankAccount
class, you might want a public getAccountNumber() method, so that clients
could retrieve information about their bank accounts, but youwould probably
not want a public getAccountPassword() method or a public
setAccountBalance() method.

The Scope of Parameters, Variables, and Methods

The scope of a variable or method refers to where it Scope can be used in a


program.
A parameter’s scope is limited to the body of the method in which it is
declared. Variables that are declared in the body of a method have scope
which extends from the point where they are declared to the end of the block
of code in which they are declared. Parameters are local variables which are
declared in the parameter list of a method’s header and which have initial
values specified by the arguments in a method call.
The scope of a parameter is the same as the scope of a variable declared at
the very Local scope beginning of the body of a method. Once the flow of

Instructor: Saria Eltalhi - Faculty of Information Technology Page 26


execution leaves a method, its parameters and other local variables cease to
exist. The scope of local variables is referred to as local scope

Scope. Local variables, that is, parameters and variables declared in


the body of a method, have local scope which extends from the point at
which they are defined to the end of the block of code in which they are
defined. In particular, the scope of a parameter is the entire body of the
method in which it is declared. [2] p102

Note
– This example uses public methods because we have not yet explained
about private.

Once you learn about private, your strategy is this:


• If you want code that uses your class to access the method, make it
public.
• If your method is called only by other methods in the same class, make it
private.
• Make it private unless you have a specific reason to do otherwise

2.7 Putting them together: An OOP Example

A class called Circle is to be defined as illustrated in the class diagram. It contains


two variables: radius (of type double) and color (of type String); and three
methods: getRadius(), getColor(), and getArea().

Three instances of Circles called c1, c2, and c3 shall then be constructed with their
respective data members, as shown in the instance diagrams.

UML notation
for objects

Figure :Classes and objects can be represented using UML notations.


The source codes for Circle.java is as follows:
// Define the Circle class

Instructor: Saria Eltalhi - Faculty of Information Technology Page 27


public class Circle { // Save as "Circle.java"
// Private variables
private double radius;
private String color;
// Public methods
public double getRadius() {
return radius;
}

public void setRadius( double rd) {


radius=rd;
}

public String getColor() {


return color;
}

public void setColor(String co) {


color=co;
}

public double getArea() {


return radius*radius*Math.PI;
}
A class that contains method main begins the execution of a Java application.
Class Circle is not an application because it does not contain main.
Notice that the Circle class does not have a main() method.

Hence, it is NOT a standalone program and you cannot run the Circle class
by itself

public class TestCircle { // Save as "TestCircle.java"

public static void main(String[] args) { // Execution entry point


// Construct an instance of the Circle class called c1

Circle c1 = new Circle();


C1. setRadius(2.0);
C1. setColor("blue");

System.out.println("Radius is " + c1.getRadius()+ " Color is "


+
c1.getColor() + " Area is " +
c1.getArea());

// Construct another instance of the Circle class called c2


Circle c2 = new Circle();
C2. setRadius(2.0);
C2. setColor("red");

Instructor: Saria Eltalhi - Faculty of Information Technology Page 28


System.out.println("Radius is " + c2.getRadius()+ " Color is "
+
c2.getColor()+ " Area is " +
c2.getArea());

// Construct yet another instance of the Circle class called


c3
Circle c3 = new Circle();
C3. setRadius(1.0);
C3. setColor("red");

System.out.println("Radius is " + c3.getRadius()


+ " Color is " + c3.getColor()
+ " Area is " + c3.getArea());
} }
A key part of enabling the JVM to locate and call method main to begin the
application’s execution is the static keyword, which indicates that main is a
static method. A static method is special, because you can call it without first
creating an object of the class in which the method is declared. We discuss
static methods later.

Any class can contain a main method. The JVM invokes the main method
only in the class used to execute the application. If an application has
multiple classes that contain main, the one that’s invoked is the one in the
class named in the java command

Notes:
1. Class methods can access only the class variables and the class
constants of the class.
2. Instance methods, including constructors, can access all types of data
members.
3. Class methods cannot call instance methods of the same class.
4. Instance methods can call all other methods of the same class

Instructor: Saria Eltalhi - Faculty of Information Technology Page 29


Non Access Modifiers:
Java provides a number of non-access modifiers to achieve many other functionality.

 The static modifier for creating class methods and variables


 The final modifier for finalizing the implementations of classes, methods, and variables.
 The abstract modifier for creating abstract classes and methods.
 The synchronized and volatile modifiers, which are used for threads.

 Static modifier:

8.7 Static Variables, Constants, and Methods

The data field radius in the circle class known as an instance variable. An
instance variable is tied to a specific instance of the class; it is not shared
among objects of the same class.

class Circle
{
/** The radius of this circle */
double radius = 1.0;
}

The static keyword in java is used for memory management mainly. We can
apply java static keyword with variables, methods, blocks and nested class.

The static keyword belongs to the class than instance of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)

If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all
objects (that is not unique for each object) e.g. company name of
employees,college name of students etc.
 The static variable gets memory only once in class area at the time of
class loading.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 30


Instance members versus static members
Instance members are fields or methods declared without the static
modifier. Fields and methods declared with the keyword static are static
members. If they are declared without the keyword static, we will refer to them
as instance members. The next subsection explains the distinction between
instance and static members.

Static fields and methods


Static fields are used when we have a variable that all the members of
some class need to share. Typically, this is a symbolic constant, but it need
not be. When a class variable is declared static, only one instance of the
variable is ever created. It is not part of any instance of the class. Instead, it
behaves like a single global variable but with the scope of the class. In other
words, in the declaration

public class Sample


{
private int x;
private static int y;
}

each Sample object stores its own x, but there is only one shared y. A common
use of a static field is as a constant

Let us modify the Circle class by adding a static variable numberOfObjects to


count the number of circle objects created. When the first object of this class
is created, numberOfObjects is 1. When the second object is created,
numberOfObjects becomes 2.[4]

Static variables are shared by all the instances of the same class.

To declare a static variable or define a static method, put the modifier static
in the variable or method declaration. The static variable numberOfObjects
and the static method getNumberOfObjects() can be declared as follows

Static int numberOfObjects;

Instructor: Saria Eltalhi - Faculty of Information Technology Page 31


Static int getNumberObjects( ) { return numberOfObjects; }

Use ClassName.methodName(arguments) to invoke a static method and


ClassName. staticVariable to access a static variable. This improves
readability, because the user can easily recognize the static method and data
in the class.

The rule to remember is never to initialize the class variables in the constructor.

 Advantage of static variable


It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable


class Student{
int rollno;
String name;
String college="ITS";
}

Suppose there are 500 students in my college, now all instance data members will
get memory each time when object is created. All students have its unique rollno and
name so instance data member is good. Here, college refers to the common property
of all objects. If we make it static, this field will get memory only once.

Java static property is shared to all objects.

Example of static variable


//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8( int r, String n) {


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 32


Output:111 Karan ITS
222 Aryan ITS

 Program of counter without static variable

In this example, we have created an instance variable named count which is


incremented in the constructor. Since instance variable gets the memory at the time
of object creation, each object will have the copy of the instance variable, if it is
incremented, it won't reflect to other objects. So each objects will have the value 1 in
the count variable.

class Counter{
int count=0; //will get memory when instance is created
Counter() { count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:1
1
1

 Program of counter by static variable


As we have mentioned above, static variable will get the memory only once,
if any object changes the value of the static variable, it will retain its value.
class Counter2 {
static int count=0; //will get memory only once and retain its value

Counter2() {
count++;
System.out.println(count);
}

public static void main(String args[]) {

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 33


}

Output:1
2
3

 Static method

A static method is a method that does not need a controlling object, and thus
is typically called by supplying a class name instead of the controlling object.
The most common static method is main.

Other static methods are found in the Integer and Math classes. Examples
are the methods Integer.parseInt, Math.sin, and Math.max. Access to a static
method uses the same visibility rules as do static fields.

If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than object of a class.


 A static method can be invoked without the need for creating an
instance of a class.
Call a static method through the class name

– ClassName.functionName(arguments);
 Static method can access static data member (do not access any non-
static methods or fields within their class) and can change the value of
it.

Also called “class methods” (vs. “instance methods”)

 Example: Math.cos
The Math class has a static method called cos that expects a double
precision number as an argument. So, you can call Math.cos(3.5)
without ever having any object (instance) of the Math class
double cosine = Math.cos(someAngle);

 Note on the main method


Since the system calls main without first creating an object, static
methods are the only type of methods that main can call directly (i.e.
without building an object and calling the method of that object)

Example of static method


//Program of changing the common property of all objects(static field).

class Student9 {
int rollno;

Instructor: Saria Eltalhi - Faculty of Information Technology Page 34


String name;
static String college = "ITS";

static void change() { college = "BBDIT"; }


Student9 (int r, String n){
rollno = r;
name = n;
}
void display () { System.out.println(rollno+" "+name+" "+college); }

public static void main(String args[]) {

Student9.change();

Student9 s1 = new Student9 (111,"Ahmed");


Student9 s2 = new Student9 (222,"Marwa");
Student9 s3 = new Student9 (333,"Asma");

s1.display();
s2.display();
s3.display();
}
}

Output:111 Ahmed BBDIT


222 Marwa BBDIT
333 Asma BBDIT

Another example of static method that performs normal calculation


//Program to get cube of a given number by static method

class Calculate {
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
} }

Output:125

Instructor: Saria Eltalhi - Faculty of Information Technology Page 35


 Restrictions for static method
There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-
static method directly.
2. this and super cannot be used in static context.

class A{
int a=40; //non static

public static void main(String args[]){


System.out.println(a);
}
}

Output:Compile Time Error

Constants in a class are shared by all objects of the class. Thus, constants
should be declared final static. For example, the constant PI in the Math
class is defined as:

final static double PI = 3.14159265358979323846;

When a method is declared as a static method, there is no implicit this


reference.
As such, it cannot access instance data or call instance methods, without
providing an object reference. In other words, from inside getTicketCount,
unqualified access of serialNumber would imply this.serialNumber, but since
there is no this, the compiler will issue an error message. Thus, a nonstatic
field, which is part of each instance of the class, can be accessed by a static
class method only if a controlling object is provided

class Ticket
{
private int serialNumber;
private static int ticketCount = 0; A static method has no
implicit this reference, and
can be invoked without an
publicTicket) ({ object reference.
System.out.println( "Calling constructor;) "
serialNumber = ++ticketCount; }

public int getSerial ) ( { return serialNumber; }

public String toString) ( { return "Ticket #" + getSerial;) ( }


public static int getTicketCount) ( { return ticketCount; }
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 36


class TestTicket
{
public static void main( String [ ] args)
{
Ticket t1;
Ticket t2;

System.out.println( "Ticket count is + " Ticket.getTicketCount) ();


t1 = new Ticket) (;
t2 = new Ticket) (;

System.out.println( "Ticket count is + " Ticket.getTicketCount) ();

System.out.println( t1.getSerial) ( );
System.out.println( t2.getSerial) ( );
}
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 37


Final Keyword
Final keyword is also known as a final modifier in Java. You can use a final
modifier with class, method, and variables in Java.
The java final keyword can be used in many context.

1. variable
2. method
3. class

The final keyword can be applied with the variables; a final variable that have
no value it is called blank final variable or uninitialized final variable. It can be
initialized in the constructor only. The blank final variable can be static also
which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.

Final variable
If you make any variable as final, you cannot change the value of final
variable(It will be constant).
class Bike9{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}}

Class BikeMain {
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();

}//end of class
}

A field that is both static and final has only one piece of storage that cannot
be changed.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 38


Inheritance

Object-oriented programming allows you to derive new classes from existing


classes. This is called inheritance. Inheritance is an important and powerful
feature in Java for reusing software. Suppose you are to define classes to model
circles, rectangles, and triangles. These classes have many common features.
What is the best way to design these classes so to avoid redundancy and make
the system easy to comprehend and easy to maintain? The answer is to use
inheritance.

Inheritance provides re-usability of code and can be used to add additional


features to an existing class, without modifying it

Common sets of attributes and methods can be organized into superclasses.


Typically, classes are arranged in a hierarchy whereby the superclasses, or
general classes, are at the top, and the subclasses, or specific classes, are at
the bottom
In next Figure, person is a superclass to the classes Doctor and Patient.
Doctor, in turn, is a superclass to general practitioner and specialist.

The relationship between the class and its superclass is known as the
A-Kind-Of (AKO) relationship

Class Hierarchy

General practitioner is A-Kind-Of doctor, which is A-Kind-Of person.

Notice how much more efficient hierarchies of object classes are than the
same objects without a hierarchy in next figure

Instructor: Saria Eltalhi - Faculty of Information Technology Page 39


Types of Inheritance
Various types of inheritance are supported by java. These are:

1. When a subclass inherits properties from one base class, it


Single Inheritance -
is called single inheritance. In single inheritance, there is only one base class
and one derived class.

When two or more subclasses inherit properties from a


2. Hierarchical Inheritance -
single base class, It is known as Hierarchical inheritance. In hierarchical
inheritance , the feature of one class may be inherited by more than one
class.

3. In multilevel Inheritance, a class is derived from an


Multilevel Inheritance -
already derived class. The transitive nature of inheritance is reflected by this
form of inheritance.

4. When two or more type of inheritance are required to code


Hybrid Inheritance -
a program, such type of inheritance is called hybrid inheritance.

5. Multiple Inheritance: not support by java

Inheritance Rules

 all fields and methods of the superclass are inherited by the subclass
 inheritance creates an is-a relationship - an instance of the subclass is
also considered an instance of the superclass
 a subclass is typically a more specialized version of its superclass
 a subclass can NOT refer to private methods and fields of its superclass

Extends Keyword
extends is the keyword used to inherit the properties of a class. Below given
is the syntax of extends keyword.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 40


class Super { ..... }
class Sub extends Super {
.....
.....
}

Why multiple inheritance is not supported in Java


 To remove ambiguity.
 To provide more maintainable and clear design.

Access Control and Inheritance


The following rules for inherited methods are enforced:

1. Methods declared public in a superclass also must be public in all


subclasses.

2. Methods declared protected in a superclass must either be protected


or public in subclasses; they cannot be private.

3. Methods declared private are not inherited at all, so there is no rule


for them.

Using protected access offers an intermediate level of access between public and
private public members of the superclass become public members of the subclass,
and protected members of the superclass become protected members of the
subclass. A superclass’s private members are not accessible outside the class itself.

The super keyword


The super keyword is similar to this keyword. The super keyword in Java is a
reference variable which is used to refer immediate parent class object.
 It is used to differentiate the members of superclass from the members
of subclass, if they have same names.
 It is used to invoke the superclass constructor from subclass.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 41


The most common use of the super keyword is to eliminate the confusion
between superclasses and subclasses that have methods with the same
name.
super keyword performs important role in three places
 Super keyword At Variable Level
 Super keyword At Method Level
 Super keyword At Constructor Level

To understand the super keyword, you should have a basic understanding


of Inheritance and Polymorphism.

Program using super keyword al variable level

class Employee
{
float salary=10000; }

class HR extends Employee


{
float salary=20000;
void display() {
System.out.println("Salary: "+super.salary);//print base class salary
}}

class Supervarible {
public static void main(String[] args) {
HR obj=new HR();
obj.display();
}}

Super Keyword at Method Level


class Animal { // Superclass (parent)
public void animalSound() {
System.out.println("The animal makes a sound");
}}

class Dog extends Animal { // Subclass (child)


public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}}

public class Main {


public static void main(String args[]) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 42


Calling Superclass Constructors
The syntax to call a superclass constructor is:
super(), or super(parameters);

When we create the object of sub class, the new keyword invokes
the constructor of child class, which implicitly invokes the constructor of
parent class. So the order to execution when we create the object of child
class is: parent class constructor is executed first and then the child class
constructor is executed. It happens because compiler itself adds super()(this
invokes the no-arg constructor of parent class) as the first statement in the
constructor of child class.

class Parentclass {
Parentclass(){
System.out.println("Constructor of parent class"); }
}
class Subclass extends Parentclass {
Subclass(){
/* Compile implicitly adds super() here as the
* first statement of this constructor. */
System.out.println("Constructor of child class");
}
Subclass(int num) {
/* Even though it is a parameterized constructor.
* The compiler still adds the no-arg super() here */
System.out.println("arg constructor of child class");
}
void display() {
System.out.println("Hello!");
}
Public class MainSub{
public static void main(String args[]){
/* Creating object using default constructor. This
* will invoke child class constructor, which will
* invoke parent class constructor */

Subclass obj= new Subclass();


obj.display(); //Calling sub class method
/* Creating second object using arg constructor
* it will invoke arg constructor of child class which will
* invoke no-arg constructor of parent class automatically */
Subclass obj2= new Subclass(10);
obj2.display();
}}}
Output:
Constructor of parent class
Constructor of child class
Hello!
Constructor of parent class
arg constructor of child class
Hello!

Instructor: Saria Eltalhi - Faculty of Information Technology Page 43


Constructor inheritance

When constructing an object of a subclass, the subclass constructor first invokes its
superclass constructor before performing its own tasks. If the superclass is derived
from another class, the superclass constructor invokes its parent-class constructor
before performing its own tasks. This process continues until the last constructor
along the inheritance hierarchy is called. This is constructor chaining.

public class Person {


Person(){
System.out.println("(1) Performs Person's tasks"); }
}

public class Patient extends Person {


Patient(){
this("(2) Invoke Patient's overloaded constructor");
System.out.println("(3) Performs Patient's tasks ");
}
Patient(String s) { System.out.println(s); }
}

public class InPatient extends Patient {


InPatient() {
System.out.println("(4) Performs Inpatient's tasks");
}}

class Main {
public static void main(String[] args) {
new InPatient();
}}

Output:
(1) Performs Person's tasks
(2) Invoke Patient's overloaded constructor
(3) Performs Patient's tasks
(4) Performs Inpatient's tasks

Caution
If a class is designed to be extended, it is better to provide a no-arg constructor to
avoid programming errors

class Fruit {
public Fruit (String name) {
System.out.println("Fruit's constructor is invoked"); }
}
public class Apple extends Fruit {
}

Class AppleMain {
public static void main(String[] args) {
new Apple ();
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 44


Since no constructor is explicitly defined in Apple, Apple’s default no-arg constructor is
defined implicitly. Since Apple is a subclass of Fruit, Apple’s default constructor
automatically invokes Fruit’s no-arg constructor. However, Fruit does not have a no-arg
constructor, because Fruit has an explicit constructor defined. Therefore, the program cannot
be compiled.

Consider the following Class Diagram:


The GeometricObject class is the superclass for Circle and Rectangle

Instructor: Saria Eltalhi - Faculty of Information Technology Page 45


Instructor: Saria Eltalhi - Faculty of Information Technology Page 46
You might attempt to use the data fields color and filled directly in the constructor as
follows:

public Circle4(double radius, String color, boolean filled)


{
this.radius = radius;
this.color = color; // Illegal private member in base class
this.filled = filled; // Illegal

Instructor: Saria Eltalhi - Faculty of Information Technology Page 47


Instructor: Saria Eltalhi - Faculty of Information Technology Page 48
The output:

Instructor: Saria Eltalhi - Faculty of Information Technology Page 49


Association, Composition and Aggregation

Association is a relation between two separate classes which establishes


through their Objects. Association can be one-to-one, one-to-many, many-to-
one, many-to-many. In Object-Oriented programming, an Object
communicates to another object to use functionality and services provided by
that object. Composition and Aggregation are the two forms of association.

Has-A Relationship

When an object of one class is created as a data member inside another


class, it is called Has-A relationship.
In other words, a relationship in which an object of one class has a
reference to an object of another class or another instance of the same class
is called Has-A relationship in Java.
1. A most common example of Has-A relationship in Java is “A person has
an address”.
Has-A relationship denotes a whole-part relationship where a part cannot
exist without the whole. In the above example, the person represents the
whole and the address represents the part. A part cannot exist by itself.
Person class has an instance variable of type Address as shown in the below
code
public class Address {
// Code goes here.
}
public class Person {
// Person has-a Address.
Address addr = new Address();

// Other codes go here.


}

Look at the above figure where an object of class Address is created as a


data member inside another class Person. This relationship is known as
Has-A relationship.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 50


Types of Has-A Relationship
There are two types of Has-A relationship that are as follows:
a. Aggregation
b. Composition
Aggregation: Aggregation is one of the core concepts of object-oriented
programming. It focuses on establishing a Has-A relationship between two
classes.
In other words, two aggregated objects have their own life cycle but one of the
objects has an owner of Has-A relationship and child object cannot belong to
another parent object.
For example, a library has students. If the library is destroyed, students will
exist without library.
Aggregation is a term which is used to refer one way relationship between two
objects. For example, Student class can have reference of Address class but vice
versa does not make sense
For example, Student class can have reference of Address class but vice versa
does not make sense.
The HAS-A relationship is based on usage, rather than inheritance. In other
words, class A has-a relationship with class B, if class A has a reference to
an instance of class B.
class Author {
String authorName;
int age;
String place;

Author(String name, int age, String place) {


this.authorName = name;
this.age = age;
this.place = place;
}}

class Book {
String name;
int price;
Author auther;
Book(String n, int p, Author auther) {
this.name = n;
this.price = p;
this.auther = auther;
}}
class BookApp {
public static void main(String[] args) {
Author auther = new Author("Ahmen", 42, "Benghazi");
Book b = new Book("Java for Begginer", 800, auther);
System.out.println("Book Name: "+b.name);
System.out.println("Book Price: "+b.price);

Instructor: Saria Eltalhi - Faculty of Information Technology Page 51


System.out.println("------------Auther Details----------");
System.out.println("Auther Name: "+b.auther.authorName);
System.out.println("Auther Age: "+b.auther.age);
System.out.println("Auther place: "+b.auther.place);
}}

Output
Book Name: Java for Begginer
Book Price: 800
------------Author Details----------
Auther Name: Ahmed
Auther Age: 42
Auther place: Benghazi

Composition: Composition is another one of the core concepts of object-


oriented programming. It focuses on establishing a strong Has-A relationship
between the two classes.
In other words, two composited objects cannot have their own life cycle. That
is, a composite object cannot exist on its own. If one composite object is
destroyed, all its parts are also be deleted.
For example, a house can have multiple rooms. A room cannot exist
independently and any room cannot belong to two different houses. If the
house is destroyed, all its rooms will be automatically destroyed.
For example a class Car cannot exist without Engine, as it won't be functional
anymore.
class Car {
private Engine engine;
Car(Engine en) {
engine = en;
}}

Composition is a design technique, not a feature of Java but we can achieve


it using Java code.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 52


Overriding Methods

A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to
modify the implementation of a method defined in the superclass. This is referred to as
method overriding

method overriding refers to the ability of a subclass to re-implement an


instance method inherited from a superclass. Let’s take a look at the
following class diagram:

the keyword super can be used to call overridden superclass methods

Overriding vs. Overloading

Overloading means to define multiple methods with the same name but
different signatures.

Overriding means to provide a new implementation for a method in the


subclass. The method is already defined in the superclass. To override a
method, the method must be defined in the subclass using the same
signature and the same return type

Overloading Overriding
Must have at least two methods by the same Must have at least one method by the same
name in the class. name in both parent and child classes.
Must have a different number of parameters. Must have the same number of parameters.
parameter must be different. Must have the same parameter types.

Overloading is known as compile-time Overriding is known as runtime


polymorphism. polymorphism.
Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 53


Overloading: Take a look at the code below:
//A class for adding upto 5 numbers
class Sum {
int add(int n1, int n2) {
return n1+n2;
}
int add(int n1, int n2, int n3) {
return n1+n2+n3;
}
int add(int n1, int n2, int n3, int n4) {
return n1+n2+n3+n4;
}
int add(int n1, int n2, int n3, int n4, int n5) {
return n1+n2+n3+n4+n5;
}
public static void main(String args[]) {
Sum obj = new Sum();
System.out.println("Sum of two numbers: "+obj.add(20, 21));
System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
}}

Overriding Take a look at the code below:


class CarClass {
public int speedLimit() {
return 100;
}
}

class Ford extends CarClass{


public int speedLimit() {
return 150;
}
public static void main(String args[]) {
CarClass obj = new Ford();
int num= obj.speedLimit();
System.out.println("Speed Limit is: "+num);
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 54


Abstraction

The abstraction technique aims to separate the implementation details of a


class from its behavior

Abstraction focuses on the behavior of an object


Abstraction can be achieved with either abstract classes or interfaces

Abstract Classes and Methods


1. Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).

2. Abstract method: can only be used in an abstract class, and it does


not have a body. The body is provided by the subclass (inherited
from)

Abstract class
Abstract classes are like regular classes, but you cannot create instances of
abstract classes using the new operator
 Abstract classes may or may not contain abstract methods (have both abstract
and regular methods)

 But, if a class has at least one abstract method, then the class must be
declared abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all
the abstract methods in it.

public abstract class Employee {

private String name;


private String address;
private int number;

public Employee(String name, String address, int number) {


System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}

public double computePay() {


System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);

Instructor: Saria Eltalhi - Faculty of Information Technology Page 55


}

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public int getNumber() {


return number;
}
}

public class Engineer extends Employee {


private double salary;

public Engineer (String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}

public void mailCheck() {


System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with salary " + salary);
}

public double getSalary() {


return salary;
}

public void setSalary(double newSalary) {


if(newSalary >= 0.0) {
salary = newSalary;
} }

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 56


Here, you cannot instantiate the Employee class, but you can instantiate the
Engineer Class, and using this instance you can access all the three fields and
seven methods of Employee class as shown below.

public class AbstractDemo {

public static void main(String [] args) {


Engineer s = new Engineer ("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Engineer ("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}

Abstract Methods
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can declare
the method in the parent class as an abstract.
 abstract keyword is used to declare the method as abstract.
 You have to place the abstract keyword before the method name in the method
declaration.
 An abstract method contains a method signature, but no method body.
 Instead of curly braces, an abstract method will have a semoi colon (;) at the
end.

Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 57


Following is an example of the abstract method.

In page 45, GeometricObject was defined as the superclass for Circle and
Rectangle. GeometricObject models common features of geometric objects.
Both Circle and Rectangle contain the getArea() and getPerimeter() methods
for computing the area and perimeter of a circle and a rectangle. Since you
can compute areas and perimeters for all geometric objects, it is better to
define the getArea() and getPerimeter() methods in the GeometricObject class.
However, these methods cannot be implemented in the GeometricObject
class, because their implementation depends on the specific type of geometric
object. Such methods are referred to as abstract methods and are denoted
using the abstract modifier in the method header. After you define the
methods in GeometricObject, it becomes an abstract class. Abstract classes
are denoted using the abstract modifier in the class header. In UML graphic
notation, the names of abstract classes and their abstract methods are
italicized

Instructor: Saria Eltalhi - Faculty of Information Technology Page 58


public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;

/** Construct a default geometric object */


protected GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with color and filled value */
protected GeometricObject(String color, boolean filled) {
dateCreated = new java.util.Date()
this.color = color;
this.filled = filled;
}

/** Return color */


public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
this.color = color;
}
/** Return filled. Since filled is boolean, * the get method is named isFilled */
public boolean isFilled() {
return filled;
}
/** Set a new filled */
public void setFilled(boolean filled) {
this.filled = filled;
}
/** Get dateCreated */
public java.util.Date getDateCreated() {
return dateCreated;
}

/** Return a string representation of this object */


public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}

/** Abstract method getArea */


public abstract double getArea();
/** Abstract method getPerimeter */
public abstract double getPerimeter();

Instructor: Saria Eltalhi - Faculty of Information Technology Page 59


//abstract class
public abstract class Person {

private String name;


private String gender;

public Person(String nm, String gen){


this.name=nm;
this.gender=gen;
}
//abstract method
public abstract void work();

@Override
public String toString(){
return "Name="+this.name+"::Gender="+this.gender;
}
public void changeName(String newName) {
this.name = newName;
}
}

Notice that work () is an abstract method and it has no-body. Here is a


concrete class example extending an abstract class in java.

public class Employee extends Person {


private int empId;
public Employee(String nm, String gen, int id) {
super(nm, gen);
this.empId=id;
}
@Override
public void work() {
if(empId == 0)
System.out.println("Not working");
else
System.out.println("Working as employee!!");
}}
Public class MainEmployee {
public static void main(String args[]){
//coding in terms of abstract classes
Employee student = new Employee("Dove","Female",0);
Employee employee = new Employee("Pankaj","Male",123);
student.work();
employee.work();
//using method implemented in abstract class - inheritance
employee.changeName("Pankaj Kumar");
System.out.println(employee.toString());
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 60


Final methods
There are two reasons for final methods. The first is to put a “lock” on the
method to prevent any inheriting class from changing its meaning. This is
done for design reasons when you want to make sure that a method’s
behavior is retained during inheritance and cannot be overridden.

Final classes
When you say that an entire class is final (by preceding its definition with the
final keyword), you state that you don’t want to inherit from this class or allow
anyone else to do so. In other words, for some reason the design of your class
is such that there is never a need to make any changes, or for safety or
security reasons you don’t want subclassing

final class A {
int i = 7;
int j = 1;

void f() {}
}

class B extends A {}

// error: Cannot extend final class A

Instructor: Saria Eltalhi - Faculty of Information Technology Page 61


Interfaces
An interface is used for full abstraction. Abstraction is a process where you
show only “relevant” data and “hide” unnecessary details of an object from
the user. It is used to achieve abstraction and multiple inheritance in Java.

Interface looks like a class but it is not a class. An interface can have methods
and variables just like the class but the methods declared in interface are by
default abstract (only method signature, no body). Also, the variables declared
in an interface are public, static & final by default.

methods in interfaces do not have body, they have to be implemented by the


class before you can access them. The class that implements interface must
implement all the methods of that interface

any number of classes can implement an interface. Also, one class can
implement any number of interfaces.

Why use Java interface?

 It is used to achieve total abstraction.


 Since java does not support multiple inheritances in the case of class, by
using an interface it can achieve multiple inheritances

Syntax:

access interface name {


return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;

interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 62


class implements interface but an interface extends another interface

class Demo implements MyInterface


{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}

Key points:

 We can’t instantiate an interface in java. Like abstract classes,


interfaces cannot be used to create objects
 Interface methods do not have a body - the body is provided by the
"implement" class
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 Interface cannot be declared as private or protected.
 On implementation of an interface, you must override all of its
methods
 A class that implements interface must implements all the methods in
interface
 A class can implement more than one interface.
 An interface can extends another interface
 It is used to achieve multiple inheritance.

Java Interface also represents the IS-A relationship.


Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 63


Therefore, the following interface definitions are equivalent:

interface Try
{
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}

All of the above statements are identical.

Interface variables must be initialized at the time of declaration otherwise


compiler will throw an error.

interface Try
{
int x; //Compile-time error
}

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an


interface extends another interface, but a class implements an interface.

// A simple interface

interface Player
{
final int id = 10;
int move();
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 64


Difference Between Class and Interface

Class Interface

In an interface, you can’t


In class, you can instantiate
1. instantiate variables and create
variables and create an object.
an object.

The interface cannot contain


Class can contain concrete(with
2. concrete(with implementation)
implementation) methods
methods)

The access specifiers used with


In Interface only one specifier is
3. classes are private, protected,
used- Public.
and public.

// A simple interface
interface In1 {

final int a = 10; // public, static and final


void display(); // public and abstract
}

// A class that implements the interface.


class TestClass implements In1 {

public void display(){


System.out.println("Geek");
}

public static void main(String[] args)


{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}}

Output
Geek
10

Instructor: Saria Eltalhi - Faculty of Information Technology Page 65


interface Vehicle {

// all are the abstract methods.


void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}

class Bicycle implements Vehicle{


int speed;
int gear;

// to change gear - @Override


public void changeGear(int newGear){
gear = newGear;
}

// to increase speed - @Override


public void speedUp(int increment){
speed = speed + increment;
}

// to decrease speed - @Override


public void applyBrakes(int decrement){
speed = speed - decrement;
}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}
}

class Bike implements Vehicle {


int speed;
int gear;

// to change gear - @Override


public void changeGear(int newGear){
gear = newGear;
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 66


// to increase speed - @Override
public void speedUp(int increment){
speed = speed + increment;
}

// to decrease speed - @Override


public void applyBrakes(int decrement){
speed = speed - decrement;
}

public void printStates() {


System.out.println("speed: " + speed
+ " gear: " + gear);
}
}

class GFG {
public static void main (String[] args) {

// creating an inatance of Bicycle


Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);

System.out.println("Bicycle present state :");


bicycle.printStates();

// creating instance of the bike.


Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);

System.out.println("Bike present state :");


bike.printStates();
}
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 67


Output
Bicycle present state :
speed: 2 gear: 2
Bike present state :
speed: 1 gear: 1

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple


interfaces, it is known as multiple inheritance .

interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 68


Output
Animal is eating
Animal is travelling

Interface inheritance
A class implements an interface, but one interface extends another interface.

1. interface Printable{
void print();
2. }
3. interface Showable{
4. void show();
5. }
6. class A7 implements Printable,Showable{
7. public void print(){System.out.println("Hello");}
8. public void show(){System.out.println("Welcome");}
9.
10. public static void main(String args[]){
11. A7 obj = new A7();
12. obj.print();
13. obj.show();
14. } }

Output
Hello
Welcome

Multiple Inheritance Without Ambiguity

interface InterfaceOne {
public void disp();
}
interface InterfaceTwo {
public void disp();
}

public class Three implements InterfaceOne,InterfaceTwo {


@Override
public void disp() {
System.out.println("display() method implementation");
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 69


Public MainApp {
public static void main(String args[]) {
Three T = new Three ();
T.disp();
}}

In Java multiple class to class inheritance is prohibited to avoid dead


diamond problem and Interface is used to implement the multiple
inheritance.

An interface can inherit other interfaces using the extends keyword. Such an
interface is called a subinterface.

interface Animal {
void eat();
}

interface Mammal extends Animal {


void breastFeed();
}

interface WingedAnimal extends Animal {


void flap();
}

class Bat implements Mammal, WingedAnimal {


public void eat() { @Override
System.out.println("Eating");
}

public void breastFeed() { @Override


System.out.println("Feeding");
}

public void flap() { @Override


System.out.println("Flying");
}
public void doFly(WingedAnimal ani) {
ani.flap();
}

public static void doFeed(Mammal ani) {


ani.breastFeed();
}
}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 70


public class MultipleInheritance {
public static void main(String [] args) {
Bat bat = new Bat();
bat .doFly(bat);
Bat .doFeed(bat);
}

In this example Bat implements both Mammal and WingedAnimal interfaces.


Therefore, Bat can be sent to a method with a parameter Mammal and to
another method with a parameter WingedAnimal parameter. In other words,
Bat IS-A Mammal as well as Bat IS-A WingedAnimal.

example on the multiple inheritance with interface.

interface I1 {
int i = 123;
void printI1();
}

interface I2 {
public static int j = 555;
void printI2();
}

class A implements I1, I2{


public int aValue = 999;

public void printI1() {


System.out.println("I am from I1 " + i);
}
public void printI2() {
System.out.println("I am from I2 " + j);
}
public void printA() {
System.out.println("I am from A " + aValue );
}}

class Demonstration_98 {
public static void main (String[] args) {
A a = new A();
a.printA();
a.printI2();
a.printI1();
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 71


Example of "extends" with "implements"

class A {
protected int j = 1000;
void print() { System.out.println("I am from A "+j);
}
}

interface I {
public static int i = 555;
void printInterface();
}

class B extends A implements I {


public int aValue = 999;

public void printInterface () {


System.out.println("I am from I " + i);
}
public void printB() {
super.print();
printInterface();
}
}

public class Demonstration_99 {


public static void main (String [] args) {
B b = new B();
b.printB();
}
}

Output:
I am from A 1000
I am from I 555

Instructor: Saria Eltalhi - Faculty of Information Technology Page 72


Since Java 8, we can have method body in interface. But we need to make it
default method. Let's see an example:

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}

Since Java 8, we can have static method in interface. Let's see an example:
interface Drawable {
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable {
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic {
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:

drawing rectangle
27

Instructor: Saria Eltalhi - Faculty of Information Technology Page 73


Note:
Class names are nouns. Interface names may be adjectives or nouns. For
example, both java.lang.Comparable and java.awt.event.ActionListener are
interfaces. Comparable is an adjective, and ActionListener is a noun.

Class1 implements Interface1; Interface1 extends Interface1_1 and


Interface1_2. Class2 extends Class1 and implements Interface2_1 and
Interface2_2.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 74


Polymorphism
Polymorphism in Java is a concept by which we can perform a single action
in different ways. The most common use of polymorphism in OOP occurs
when a parent class reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A test is considered to be
polymorphic. In Java, all Java objects are polymorphic since any object will
pass the IS-A test for their own type and for the class Object.

Following concepts demonstrate different types of polymorphism in java.


1. Method Overloading
2. Method Overriding

There are two types of polymorphism in Java:


 compile-time polymorphism (static polymorphism) and
 runtime polymorphism. ( Dynamic polymorphism)

We can perform polymorphism in java by method overloading and method


overriding.

In the above figure, you can see, Man is only one, but he takes multiple
roles like – he is a dad to his child, he is an employee, a salesperson and
many more. This is known as Polymorphism

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Following are true for the above examples
 A Deer IS-A Animal
 A Deer IS-A Vegetarian
 A Deer IS-A Deer
 A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the
following declarations are legal –

Instructor: Saria Eltalhi - Faculty of Information Technology Page 75


Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d, a, v, o refer to the same Deer object in the heap.

Upcasting and Downcasting


A process of converting one data type to another is known
as Typecasting and Upcasting and Downcasting is the type of object
typecasting. In Java, the object can also be typecasted like the
datatypes. Parent and Child objects are two types of objects. So, there are two
types of typecasting possible for an object, i.e., Parent to Child and Child to
Parent or can say Upcasting and Downcasting.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is
known as upcasting. By using the Upcasting, we can easily access the
variables and methods of the parent class to the child class.

class A{ }
class B extends A{ }
A a=new B(); //upcasting

For upcasting, we can use the reference variable of class type or an interface
type. For Example:

interface I{ }
class A{ }
class B extends A implements I{ }

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Instructor: Saria Eltalhi - Faculty of Information Technology Page 76


Since Object is the root class of all classes in Java, so we can write B IS-A
Object.

public class One {


void m1() {
System.out.println("m1 method in class One");
} }

public class Two extends One {


void m2() {
System.out.println("m2 method in class Two");
} }

public class Test {


public static void main(String[] args) {
One o = (One)new Two(); // Upcasting. Here, super class reference o refers to sub class object.
o.m1();
// o.m2(); // Compile-time error message.
} }

Output:

m1 method in class One

One o = (One) new Two(); // Converting class Two's type into class One.

Here, sub class object type has been converted into super class type. This kind
of conversion is called upcasting or widening in java.
If we do not use cast operator in the above case, even we will not get any error
message. Java compiler will do the implicit casting
Upcasting will be done internally and due to upcasting the object is allowed
to access only parent class members and child class specified members
(overridden methods, etc.) but not all members.

Downcasting (Narrowing) in Java

When subclass(child class) reference refers to super class(parent class )object, it is


called narrowing or downcasting in java. In other words, when sub class type
is converted into super class type, it is called downcasting.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 77


Two t = (Two) new One();

Here, we are converting superclass object type into subclass type. Therefore,
we need a compulsory cast operator. If we perform it directly, Java compiler
will give compile-time error. Next figure shows simply Upcastion and
Downcastion.
simply Upcastion and Downcastion.

public class One {


void m1() {
System.out.println("m1 method in class One");
}}

public class Two extends One {


void m2() {
System.out.println("m2 method in class Two");
} }

public class Test {


public static void main(String[] args)
{
// Downcasting. Here, subclass reference t refers to superclass object.
Two t = (Two) new One();
t.m1();
t.m2();
}}

Output:

Exception in thread "main" java.lang.ClassCastException:


classCasting.One cannot be cast to classCasting.Two

Instructor: Saria Eltalhi - Faculty of Information Technology Page 78


In the above example program, we have performed downcasting directly.
Therefore, JVM is thrown an exception named ClassCastException at run
time.
So, in the case of downcasting, we cannot access any of the methods of
super class or sub class.
To overcome this problem, we will have to modify the previous code. So, look
at the following source code and modify it.

public class Test {


public static void main(String[] args)
{
One o = new Two(); // Super class reference refers to sub class object.
Two t = (Two)o; // Converting super class reference type into sub class reference type.
t.m1(); // Calling m1 method using reference variable of sub class.
t.m2(); // Calling m2 method using reference variable of sub class.
}
}

Output:

m1 method in class One


m2 method in class Two

In the above program, superclass reference type has been converted into sub
class reference type. Now, we are able to call both methods m1() and m2()
using reference variable of sub class.

Below is an example of downcasting in which both the valid and the invalid
scenarios are explained:

class Parent {
String name;

// A method which prints the data of the parent class


void showMessage() {
System.out.println("Parent method is called");
} }

// Child class
class Child extends Parent {
int age;

// Performing overriding

Instructor: Saria Eltalhi - Faculty of Information Technology Page 79


@Override
void showMessage() {
System.out.println("Child method is called");
} }

public class Downcasting {

public static void main(String[] args) {


Parent p = new Child();
p.name = "Shubham";

// Performing Downcasting Implicitly


//Child c = new Parent(); // it gives compile-time error
// Performing Downcasting Explicitly
Child c = (Child)p;

c.age = 18;
System.out.println(c.name);
System.out.println(c.age);
c.showMessage();
} }

Runtime Polymorhism( or Dynamic polymorphism)


Method overriding is a perfect example of runtime polymorphism. In this kind
of polymorphism, reference of class X can hold object of class X or an object
of any sub classes of class X. For e.g. if class Y extends class X then both of
the following statements are valid:

Y obj = new Y();


X obj = new Y(); //Parent class reference can be assigned to child object

Since in method overriding both the classes(base class and child class) have
same method, compile doesn’t figure out which method to call at compile-
time. In this case JVM(java virtual machine) decides which method to call at
runtime that’s why it is known as runtime or dynamic polymorphism.

Let’s take next program where we will override super class method in sub
class and will observe that can we access super class method and sub class
method

public class X {
public void methodA() //Base class method {
System.out.println ("hello, I'm methodA of class X");
}}

Instructor: Saria Eltalhi - Faculty of Information Technology Page 80


public class Y extends X {
public void methodA() { //Derived Class method
System.out.println ("hello, I'm methodA of class Y");
}
}
public class Z {
public static void main (String args []) {
X obj1 = new X(); // Reference and object X
X obj2 = new Y(); // X reference but Y object
obj1.methodA();
obj2.methodA();
}
}
Output:

hello, I'm methodA of class X


hello, I'm methodA of class Y

As you can see the methodA has different-2 forms in child and parent class
thus we can say methodA here is polymorphic.

class MacBook{
public void myMethod( ) {
System.out.println("Overridden Method");
}
}
public class iPad extends MacBook{
public void myMethod(){
System.out.println("Overriding Method");
}

public static void main(String args[]){


MacBook obj = new iPad();
obj.myMethod();

MacBook obj = new MacBook();


obj.myMethod(); // This would call the myMethod() of parent class MacBook
iPad obj = new iPad();
obj.myMethod(); // This would call the myMethod() of child class iPad
MacBook obj = new iPad();
obj.myMethod(); // This would call the myMethod() of child class iPad
}}

When you invoke the overriding method, then the object determines which
method is to be executed. Thus, this decision is made at the run time.

Instructor: Saria Eltalhi - Faculty of Information Technology Page 81


In the above example, the method of the child class is to be executed because
the method that needs to be executed is determined by the type of object. Since
the object belongs to the child class, the child class version of myMethod () is
called.

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
} }
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Method is overridden not the datamembers, so runtime polymorphism can't be
achieved by data members.

Compile time Polymorhism( or Static polymorphism)


A polymorphism that is resolved during compile time is known as static
polymorphism. Method overloading is an example of compile time polymorphism.

Compile time polymorphism is nothing but the method overloading in java. In simple
terms we can say that a class can have more than one methods with same name but
with different number of arguments or different types of arguments or both. Lets see
the below example to understand it better-

class X {
void methodA(int num) {

Instructor: Saria Eltalhi - Faculty of Information Technology Page 82


System.out.println ("methodA:" + num);
}
void methodA(int num1, int num2) {
System.out.println ("methodA:" + num1 + "," + num2);
}
double methodA(double num) {
System.out.println("methodA:" + num);
return num;
}
}

class Y {
public static void main (String args []) {
X Obj = new X();
double result;
Obj.methodA(20);
Obj.methodA(20, 30);
result = Obj.methodA(5.5);
System.out.println("Answer is:" + result);
}
}
Output:

methodA:20
methodA:20,30
methodA:5.5
Answer is:5.5

As you can see in the above example that the class has three variances
of methodA or we can say methodA is polymorphic in nature since it is having
three different forms. In such scenario, compiler is able to figure out the
method call at compile-time that’s the reason it is known as compile time
polymorphism.

What is the difference between Polymorphism and Inheritance in Java?


Polymorphism Inheritance
Inheritance refers to the ability of an
Polymorphism refers to the ability of an
entity to inherit the properties of
entity to take several forms
another
Polymorphism in Java is implemented Inheritance in Java is implemented on a
on a method level class level
Polymorphism enables method
invocation during compile time as well Inheritance enables code reusability
as runtime

Instructor: Saria Eltalhi - Faculty of Information Technology Page 83


– Why and When to Use "Inheritance" and "Polymorphism"?
It is useful for code reusability: reuse attributes and methods of an existing
class when you create a new class.

– Why we need Upcasting and Downcasting?

In Java, we rarely use Upcasting. We use it when we need to develop a code


that deals with only the parent class. Downcasting is used when we need to
develop a code that accesses behaviors of the child class.

– Difference between Upcasting and Downcasting

These are the following differences between Upcasting and Downcasting:

Upcasting Downcasting

1 A child object is typecasted to a The reference of the parent class object is


parent object. passed to the child class.

2 We can perform Upcasting implicitly Implicitly Downcasting is not possible.


or explicitly.

3 In the child class, we can access the The methods and variables of both the
methods and variables of the parent classes(parent and child) can be
class. accessed.

4 We can access some specified All the methods and variables of both
methods of the child class. classes can be accessed by performing
downcasting.

5 Parent p = new Parent() Parent p = new Child()


Child c = (Child)p;

Instructor: Saria Eltalhi - Faculty of Information Technology Page 84


Reference
[1]. Liang YD. Introduction to Java Programming. Comprehens. Pearson College Div;
2010. 1–1342 p.
[2] https://www.tutorialspoint.com/index.htm
[3] https://www.javatpoint.com/
[4] https://www.geeksforgeeks.org/upcasting-vs-downcasting-in-java/
[5] https://www3.ntu.edu.sg/home/ehchua/Programming/java/J3a_OOPBasics.html

Instructor: Saria Eltalhi - Faculty of Information Technology Page 85

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy