Object Oriented Programming
Object Oriented Programming
using Java
Encapsulation
Inheritance
Polymorphism
Abstraction
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.
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.
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
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
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:
Student
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.
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
Student std;
We create an object by invoking the new operator. The syntax for new is [20]
Next figure shows the distinction between object declaration and creation
Now, consider the following object declaration and two statements of object
creation:
Customer customer;
Messages and
Methods
For examples, suppose that we have a class called Circle, we can create instances of Circle as
follows:
– 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
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:
For examples:
public double getArea() {
return radius*radius*Math.PI;
}
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.
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.
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.
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).
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
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.
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;
}
}
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
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)
//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
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
public Rectangle() {
this(0, 0, 1, 1); }
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.
To use a modifier, you include its keyword in the definition of a class, method, or variable
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
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.
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
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 gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.
Note
– This example uses public methods because we have not yet explained
about private.
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
Hence, it is NOT a standalone program and you cannot run the Circle class
by itself
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
Static modifier:
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 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.
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
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
The rule to remember is never to initialize the class variables in the constructor.
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.
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
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
Counter2() {
count++;
System.out.println(count);
}
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.
– 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.
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);
class Student9 {
int rollno;
Student9.change();
s1.display();
s2.display();
s3.display();
}
}
class Calculate {
static int cube(int x){
return x*x*x;
}
Output:125
class A{
int a=40; //non static
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:
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; }
System.out.println( t1.getSerial) ( );
System.out.println( t2.getSerial) ( );
}
}
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.
The relationship between the class and its superclass is known as the
A-Kind-Of (AKO) relationship
Class Hierarchy
Notice how much more efficient hierarchies of object classes are than the
same objects without a hierarchy in next figure
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.
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.
class Employee
{
float salary=10000; }
class Supervarible {
public static void main(String[] args) {
HR obj=new HR();
obj.display();
}}
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 */
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.
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 ();
}}
Has-A Relationship
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);
Output
Book Name: Java for Begginer
Book Price: 800
------------Author Details----------
Auther Name: Ahmed
Auther Age: 42
Auther place: Benghazi
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
Overloading means to define multiple methods with the same name but
different signatures.
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.
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 Engineer (String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
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.
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
@Override
public String toString(){
return "Name="+this.name+"::Gender="+this.gender;
}
public void changeName(String newName) {
this.name = newName;
}
}
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 {}
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.
any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
Syntax:
interface MyInterface
{
/* All the methods are public abstract by default
* As you see they have no body
*/
public void method1();
public void method2();
}
Key points:
interface Try
{
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}
interface Try
{
int x; //Compile-time error
}
// A simple interface
interface Player
{
final int id = 10;
int move();
}
Class Interface
// A simple interface
interface In1 {
Output
Geek
10
class GFG {
public static void main (String[] args) {
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();
}}
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
interface InterfaceOne {
public void disp();
}
interface InterfaceTwo {
public void disp();
}
An interface can inherit other interfaces using the extends keyword. Such an
interface is called a subinterface.
interface Animal {
void eat();
}
interface I1 {
int i = 123;
void printI1();
}
interface I2 {
public static int j = 555;
void printI2();
}
class Demonstration_98 {
public static void main (String[] args) {
A a = new A();
a.printA();
a.printI2();
a.printI1();
}}
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();
}
Output:
I am from A 1000
I am from I 555
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
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.
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
All the reference variables d, a, v, o refer to the same Deer object in the heap.
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{ }
B IS-A A
B IS-A I
B IS-A Object
Output:
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.
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.
Output:
Output:
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;
// Child class
class Child extends Parent {
int age;
// Performing overriding
c.age = 18;
System.out.println(c.name);
System.out.println(c.age);
c.showMessage();
} }
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");
}}
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");
}
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.
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 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) {
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.
Upcasting Downcasting
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.