Lab 1 Revision of Object Oriented Programming Concept: Encapsulation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Lab 1

Revision of object oriented programming concept

Learning objective:
After this lab student should be able to:
• What is encapsulation? What is data hiding? How to achieve it?
• What is inheritance? Type of inheritance.
• What is polymorphism? Types of polymorphism
• Practical example and exercises?

Encapsulation
Encapsulation is a process of combining data members and functions in a single unit called class.
This is to prevent the access to the data directly, the access to them is provided through the
functions of the class. It is one of the popular feature of Object Oriented Programming (OOPs)
that helps in data hiding.
How Encapsulation is achieved in a class
To do this:
1. Make all the data members private.
2. Create public setter and getter functions for each data member in such a way that the set
function set the value of data member and get function get the value of data member.
Example
package javaapplication1;

/**
*
* @author Shuja
*/
public class Student {
private String name;
private int age ;
private int s_id;

public String getName() {


return name;
}
public int getAge() {
return age;
}

public int getS_id() {


return s_id;
}

public void setName(String name) {


this.name = name;
}

public void setAge(int age) {


this.age = age;
}

public void setS_id(int s_id) {


this.s_id = s_id;
}
}
package javaapplication1;

public class JavaApplication1 {


/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Student s1=new Student();
s1.setName("Shuja");
s1.setAge(25);
s1.setS_id(2028);

System.out.println(s1.getName());
System.out.println(s1.getAge());
System.out.println(s1.getS_id());

// TODO code application logic here


}
}

Inheritance
What is Inheritance?
Inheritance is one of the feature of Object-Oriented Programming (OOPs). Inheritance allows a
class to use the properties and methods of another class. In other words, the derived class inherits
the states and behaviors from the base class. The derived class is also called subclass and the base
class is also known as super-class. The derived class can add its own additional variables and
methods. These additional variable and methods differentiates the derived class from the base
class.
Inheritance is a compile-time mechanism. A super-class can have any number of subclasses. But
a subclass can have only one superclass. This is because Java does not support multiple inheritance.
Extends Keywords
Extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends
keyword.
class Super{
.....
.....
}

class Sub extends Super{


.....
.....
}

public class ChildClass extends BaseClass {


// derived class methods extend and possibly override
}
Example
Let’s consider a superclass Vehicle. Different vehicles have different features and properties
however there few of them are common to all. Speed, color, fuel used, size are few which are
common to all. Hence we can create a class ‘Vehicle’ with states and actions that are common to
all vehicles. The subclass of this superclass can be any type of vehicle. Example: Class Car A has
all the features of a vehicle. But it has its own attributes which makes it different from other
subclasses. By using inheritance we need not rewrite the code that we’ve already used with the
Vehicle. The subclass can also be extended. We can make a class ‘Sports Car’ which extends ‘Car’.
It inherits the features of both ‘Vehicle’ and ‘Car’.

class Vehicle {
String color;
int speed;
int size;
void attributes() {
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}

class Car extends Vehicle {


int CC;
int gears;
void attributescar() {
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}

public class Test {


public static void main(String args[]) {
Car b1 = new Car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.CC = 1000;
b1.gears = 5;
b1.attributescar();
}
}

The output is

Color of Car : Blue


Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5

Note:
The derived class inherits all the members and methods that are declared as public or protected. If
declared as private it cannot be inherited by the derived classes. The private members can be
accessed only in its own class. The private members can be accessed through assessor methods as
shown in the example below. The derived class cannot inherit a member of the base class if the
derived class declares another member with the same name.

Single Inheritance

Single inheritance is easy to understand. When a class extends another one class only then we call
it a single inheritance. The below flow diagram shows that class B extends only one class which
is A. Here A is a parent class of B and B would be a child class of A.
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

Multilevel Inheritance

Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see
in below flow diagram C is subclass or child class of B and B is a child class of A. For more
details and example refer – Multilevel inheritance in Java.
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

Hierarchical Inheritance

In such kind of inheritance one class is inherited by many sub classes. In below example class
B,C and D inherits the same class A. A is parent class (or base class) of B,C & D. Read More at
– Hierarchical Inheritance in java with example program.
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
Super keyword
The super keyword is similar to this keyword following are the scenarios where the super keyword
is used.

• 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.

Exercise

Q1 Write a parent class Account that extends class name saving account and saving account
extends account details class.

Member variables of parent and derived classes are:


Account
• Customer Name (String)
• Account Number (Integer)

Saving account
• Minimum bill (int)
• Saving Bill (int)

Account Details
• Deposits (int)
• Widthdrawls(int)

In each class make parameterize constructor and display function. Drive classes invoke super class
constructor and method using super keyword. In the main class make the object of account detail
and display the details of the account.

Polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.

Compile-time polymorphism:
Compile-Time polymorphism in java is also known as Static Polymorphism. In this process, the
call to the method is resolved at compile-time. Compile-Time polymorphism is achieved through
Method Overloading..
Example

We will do addition in java and understand the concept of compile-time polymorphism.

package staticPolymorphism;

public class Addition

void sum(int a, int b)

int c = a+b;

System.out.println(“ Addition of two numbers :” +c); }

void sum(int a, int b, int e)

int c = a+b+e;

System.out.println(“ Addition of three numbers :” +c); }

public static void main(String[] args)

Addition obj = new Addition();

obj.sum ( 30,90);

obj.sum(45, 80, 22);

}
The output of the program will be:

Sum of two numbers: 120

Sum of three numbers: 147

In this program, the sum() method was overloaded with two types with different parameters.

This is the basic concept of compile-time polymorphism in java where we can perform various
operations by using multiple methods having the same name.

Runtime polymorphism

Runtime polymorphism in java is also known as Dynamic Binding or Dynamic Method


Dispatch. In this process, the call to an overridden method is resolved dynamically at runtime
rather than at compile-time. Runtime polymorphism is achieved through Method Overriding.

Method Overriding is done when a child or a subclass has a method with the same name,
parameters and return type as the parent or the superclass, then that function overrides the function
in the superclass. In simpler terms, if the subclass provides its definition to a method already
present in the superclass, then that function in the base class is said to be overridden.

It should be noted that runtime polymorphism can only be achieved through functions and not data
members.

Overriding is done by using a reference variable of the superclass. Which method to be called
is determined based on the object which is being referred to by the reference variable. This is
also known as Upcasting.

Upcasting is done when the Parent class’s reference variable refers to the object of the child
class. For example:

Example

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

Example 1:
In this example, we are creating one superclass Animal and three subclasses, Herbivores,
Carnivores and Omnivores. Subclasses extend the superclass and override its eat() method. We
will call the eat() method by the reference variable of Parent class, i.e. Animal class. As it
refers to the base class object and the base class method overrides the superclass method, the
base class method is invoked at runtime. As Java Virtual Machine or the JVM and not the
compiler determines method invocation, it is runtime polymorphism.

class Animal{
void eat(){
System.out.println("Animals Eat");
}
}
class herbivores extends Animal{
void eat(){
System.out.println("Herbivores Eat Plants");
}
}
class omnivores extends Animal{
void eat(){
System.out.println("Omnivores Eat Plants and meat");
}
}
class carnivores extends Animal{
void eat(){
System.out.println("Carnivores Eat meat");
}
}
class main{
public static void main(String args[]){
Animal A = new Animal();
Animal h = new herbivores(); //upcasting
Animal o = new omnivores(); //upcasting
Animal c = new carnivores(); //upcasting
A.eat();
h.eat();
o.eat();
c.eat();

}
}
Exercise

Q2 Create a class named GeometricShape containing


Two data fields i.e. shapeType (a string) and area (of type double)
• A no-argument constructor to initialize all data fields with default values
“NoShape” and 0.0
• A member function named computeArea() with returning value of area data
field.
• A member function named show() to display the details associated with an
instance of this class.
• Derive a class named Rectangle from class GeometricShape that includes the
data members for the length and width of a rectangle, respective mutator and
accessor functions to set and get values of length and width, and Overriding
function named computeArea() to compute the area of rectangle
(length x width).
• Overriding function named show() to display the details associated with an
instance of class Rectangle
• From the Rectangle class, derive a class named Cuboid that contains
a data field named height in addition to length and width,
• Two functions named setHeight and getHeight() to set and get value of height
datafield, and an overriding function named computeArea() to calculate the
area of a cuboid (length x width x height).
• overriding function named show() to display the details associated with an
instance of class Cuboid
Implement these classes and in the main() create instances parent class and using up
casting test the functionality of overridden member functions in base classes.

You might also like