LAB (10) oop

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

JAVA SUPER KEYWORD &

POLYMORPHISM
Lab-10
LAB 10 Super Keyword and Polymorphism in Java

Lab Objectives:
1. Understanding the concept of polymorphism
2. Understand the super keyword in inheritance

Software Required:
Netbeans IDE

super Keyword in Java


Sample Code:
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}

// BoxWeight now fully implements all constructors.


class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}

class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " + vol);
System.out.println("Weight of mybox3 is " + mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
System.out.println("Weight of myclone is " + myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
System.out.println("Weight of mycube is " + mycube.weight);
System.out.println();
}
}

TASK 1: super keyword is used to refer immediate parent class instance


variable.

We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields. Perform following steps
 Create a class and its sub class both having same data member.
 Use super in child class to print the value of parent class variable.
 create a test class to implement main method with demo functionality

TASK 2: super Keyword can be used to invoke parent class method.

The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
Perform following steps
• Create a class animal with a method eat() which prints "eating"

• Create subclass of animal class with method bark() which prints "barking" and method eat()
same name as super class but it prints "eating meat"

• Write a print() method in subclass which call all the super and sub class methods.

TASK 3: super Keyword is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Create a scenario in
which above use of the super keyword is depicted.
MULTI LEVEL HIERARCHY:
TASK 4: Run the following code
class student
{
int rollno;
String name;
student(int r, String n)
{
rollno = r;
name = n;
}
void dispdatas()
{
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
}
}
class marks extends student
{
int total;
marks(int r, String n, int t)
{
super(r,n); //call super class (student) constructor
total = t;
}
void dispdatam()
{
dispdatas(); // call dispdatap of student class
System.out.println("Total = " + total);
}
}
class percentage extends marks
{
int per;

percentage(int r, String n, int t, int p)


{
super(r,n,t); //call super class(marks) constructor
per = p;
}
void dispdatap()
{
dispdatam(); // call dispdatap of marks class
System.out.println("Percentage = " + per);
}
}
class Multi_Inhe
{
public static void main(String args[])
{
percentage stu = new percentage(102689, "RATHEESH", 350, 70); //call constructor percentage
stu.dispdatap(); // call dispdatap of percentage class
}
}

Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by 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.

Usage of Java Method Overriding


Method overriding is used to provide specific implementation of a method that is already provided by its
super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Sample Code:

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}

Task 05: Consider a scenario, Bank is a class that provides functionality to get
rate of interest. But, rate of interest varies according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.
Task 06: Create Object in following manner:

Bank obj = new SBI();

QUESTIONS

Please Fill the blank space with respective answers to following questions:
Question 1: What will be the output of the following program?

class Mobile {
String str = "";
Mobile() {
str += "Mobile is : ";
}
}
class Airtel extends Mobile {
Airtel() {
str += "Airtel";
}
}
public class Docomo extends Mobile {
Docomo() {
str += "Docomo";
}
public static void main(String args[]) {
Mobile d = new Docomo();
System.out.println(d.str);
}
}
Question 2: If parent class has a constructor animal which takes two
parameters integer and a string. How will it be called in child class using
super? Write the calling line of code.

To call the constructor of the parent class (Animal) with two parameters (an integer and a string)

using super keyword in the constructor of the child class, you would write the following line of

code in the child class constructor:

class Animal {

int age;

String name;

// Parent class constructor with two parameters

Animal(int age, String name) {

this.age = age;
this.name = name;

class Dog extends Animal {

// Child class constructor

Dog(int age, String name) {

super(age, name); // Calling parent class constructor using super

Question 3: What is difference between this and super?

this:

 this is a reference to the current object.

 It can be used to refer to instance variables, instance methods, or the current class constructor
within the class.

 It is often used to differentiate between instance variables and method parameters with the
same name, or to invoke one constructor from another constructor in the same class.

super:

 super is a reference to the superclass (parent class) of the current object.

 It can be used to refer to superclass members (variables or methods) within the subclass.
 It is often used to call superclass constructors or methods from the subclass, or to access
overridden superclass methods.

Question 4: What is polymorphism? How to implement polymorphism


in java?

Polymorphism in Java refers to the ability of different objects to respond to the same
message or method call in different ways. It allows objects of different classes to be
treated as objects of a common superclass, and enables methods to be invoked
dynamically at runtime based on the type of object.

To implement polymorphism in Java:

 Use method overloading to provide multiple methods with the same name but different
parameter lists within the same class.

 Use method overriding to provide specific implementations of methods in subclasses that have
the same signature as methods in their superclasses.

 Use inheritance to create a hierarchy of classes where subclasses can be treated as instances of
their superclass, enabling polymorphic behavior.

Question 5: What will be the output of the following program?


public class MethodOverriding {
public static void main(String args[]) {
X x = new X();
Y y = new Y();
y.m2();
x.m1();
y.m1();
x = y;
x.m1();
}
}
class X {
public void m1() {
System.out.println("m1 ~ X");
}
}
class Y extends X {
public void m1() {
System.out.println("m1 ~ Y");
}
public void m2() {
System.out.println("m2 ~ Y");
}
}

THE END

You might also like