Module2 - OOP - Inheritance, Packages and Interfaces
Module2 - OOP - Inheritance, Packages and Interfaces
Interfaces:
1. Create an Array of Objects
2. Understand the Principle of OOP - Inheritance
• Problem Solving Assignment
• 1. Create an array of products with data id, name, price and sale. Display the objects in
ascending order of sales.
• 2. Describe the various forms of inheritance in Java.
1. Array of Objects Student (int id , String name , double avg)
/* datatype arr_name[] = new type[size]; {
Student s[ ] = new Student[10]; this(id,name);
datatype[] arr_name = new type[size]; this.avg = avg; }
Student[] s = new Student[10]; */ void display( )
import java.util.*; {
class Student System.out.println(id + " , " + name + ", " + avg);
{ }}
int id ; public class Filter
String name; {
double avg; public static void main(String args[])
Student(int id) {
{ Scanner sc = new Scanner(System.in);
this.id = id; System.out.println("Enter the number of
} Students");
Student(int id , String name ) int n = sc.nextInt();
{ Student s[] = new Student[n];
this(id);
this.name= name;
}
for(int i=0; i<s.length ; i++)
{
System.out.println("Enter the Student Details of ->
" +(i+1));
int x = sc.nextInt();
String str = sc.next();
double y = sc.nextDouble();
s[i] = new Student(x,str,y);
}
System.out.println("Enter the Average to display
list ");
double p = sc.nextDouble();
3. Hierarchical Inheritance
A Super class is inherited by many sub
classes.
4. Multiple Inheritance
A sub class extending more than one
super class.
5. Hybrid Inheritance
It is a combination of Multiple and
Multilevel inheritance.
Note:
Java does not support Multiple
i.e. : class C extends A,B Inheritance and Hybrid Inheritance
{ directly with classes.
//CTE Compile Time Error In Java multiple and hybrid
} inheritance is supported through
interfaces only.
Single Inheritance:
one class has only one direct super class.
area.
o We can overload a main() method , but Java will call only the main() method having string array as
argument.
class A void show() //hides show() of super class.
{ {
int i,j; // super.show();
A(int a , int b) System.out.println("k is " +k);
{ }
i=a; }
j=b; public class RideDemo
} {
public static void main(String args[])
void show() {
{ B b = new B(7,8,9);
System.out.println("i , j is " +i + "," +j); b.show(); //k is 9
} }
} }
class B extends A{
int k;
B(int a , int b , int c) {
super(a,b);
k=c;
}
Runtime Polymorphism [ Dynamic Method Dispatch]
Method Overriding forms the basis for Dynamic method dispatch.
Method overriding in java provides runtime polymorphism.
Using DMD, a call to an overridden method is resolved at runtime, rather than at compile time.
Runtime polymorphism in java implemented by using Dynamic method dispatch.
Upcasting: A super class reference variable can refer to a sub class object. I.e. When reference variable
of super class refers to the sub class object, then it is called up casting.
Eg: class A -> A is Super class
class B extends A -> B is sub class
A ref;
B b = new B();
ref = b; // upcasting
or
ref = new B(); //upcasting
// Dynamic Method Dispatch – Example1 {
class A public static void main(String args[])
{ {
void callme() A a = new A();
{ B b = new B();
System.out.println("Inside A's callme method"); C c = new C();
} A r; //reference variable of super class
} r = a;
class B extends A r.callme(); //a version using upcasting
{ r= b;
void callme() r.callme(); // b version - upcasting
{ r= c;
System.out.println("Inside B's callme method"); r.callme(); //c verrsoion - upcasting
} }
} }
class C extends A {
void callme(){
System.out.println("Inside C's callme method");
}
}
// Using run-time polymorphism-Example -2 {
class Figure Rectangl(double a, double b) {
{ super(a, b);
double dim1; }
double dim2; double area()
Figure(double a, double b) {
{ System.out.println("Inside Area for Rectangle.");
dim1 = a; return dim1 * dim2;
dim2 = b; }}
} class Triangle extends Figure {
Triangle(double a, double b)
double area() {
{ super(a, b);
System.out.println("Area for Figure is undefined."); }
return 0; double area() {
} System.out.println("Inside Area for Triangle.");
} return (dim1 * dim2) / 2;
}
}
public class DMDDemo1
{
public static void main(String args[])
{
Figure f = new Figure(10, 10);
Rectangl r = new Rectangl(9, 5);
Triangle t = new Triangle(10, 8);
Figure ref;
ref = r; //Upcasting
System.out.println("Area is " + ref.area());
ref = t;
System.out.println("Area is " + ref.area());
ref = f;
System.out.println("Area is " + ref.area());
}
}
// Dynamic Method Dispatch Example-3 {
class Bank float getRateOfInterest()
{ {
float getRateOfInterest() return 9.7f;
{ }}
return 0; class DMDDemo3
} {
} public static void main(String args[])
class SBI extends Bank {
{ Bank b=new SBI();
float getRateOfInterest() System.out.println("SBI Rate of Interest:
{ "+b.getRateOfInterest());
return 8.4f; b=new ICICI();
}} System.out.println("ICICI Rate of Interest:
class ICICI extends Bank "+b.getRateOfInterest());
{ b=new AXIS();
float getRateOfInterest() System.out.println("AXIS Rate of Interest:
{ "+b.getRateOfInterest());
return 7.3f; }}
}}
public class FinalDemo1
3. final keyword {
The final keyword in java is used to restrict the
final int SPEED_LIMIT =90;
user. void find()
final is used with a variable , a method , or a
{
class. SPEED_LIMIT=120;
}
final keyword with a variable public static void main(String args[])
A data member declared as final prevents its
{
contents from being modified.(Constant) FinalDemo1 d = new FinalDemo1();
We must initialize a final field when it is
d.find(); //Compile time Error
declared. }
The value can be initialized during declaration
}
or in the constructor.
A local variable or parameter can also be
made as “final”
final double PI = 3.1429;
PI = PI + 2; //CTE
If a class declared as final, it cannot be inherited i.e we cannot create sub class for that final class.
Simply,
abstract
class
achieves
partial
abstraction
(0 to 100%)
whereas
interface
achieves
fully
abstraction
(100%).
//Example Program on Interfaces -1
interface Bank
{ class IntDemo2
float rateOfInterest(); {
} public static void main(String[] args)
class SBI implements Bank {
{ Bank b1=new SBI(); //upcasting
public float rateOfInterest() System.out.println("ROI: of SBI
{ "+b1.rateOfInterest());
return 9.15f; Bank b2=new PNB();
} System.out.println("ROI: of PNB
} "+b2.rateOfInterest());
class PNB implements Bank }
{ }
public float rateOfInterest()
{
return 9.7f;
}
}
//Example Program on Interfaces -2 Methods and
Interfaces
/* abstract class Employee { class Emp implements Employee { //implementing
final String company; interface
final String address; public void show() {
final int pin; System.out.println(company);
abstract void show(); System.out.println(address);
} */ System.out.println(pin);
interface Employee { //defining interface }
String company="Infosys"; }
String address="hyd"; public class IntDemo4 { //accessing interface
int pin= 501232; public static void main(String args[])
void show(); {
} Emp e1 = new Emp();
e1.show();
}
}
Extending interfaces
//Example Program on Interfaces -3 public void showB(){
interface A{ System.out.println("I am from ShowB");
void showA(); }
} public void showC() {
interface B extends A{ System.out.println("I am from ShowC");
void showB(); }
} }
interface C extends B{ public class MLevel{
void showC(); public static void main(String args[]) {
} D d = new D();
class D implements C { //implementation class d.showA();
public void showA() { d.showB();
System.out.println("I am from ShowA"); d.showC();
} }
}
/ A real-world example: int speed;
Let’s consider the example of vehicles like bicycle, int gear;
car, bike………, they have common functionalities. public void changeGear(int newGear){
So we make an interface and put all these common gear = newGear;
functionalities. And lets Bicycle, Bike, car ….etc }
implement all these functionalities in their own public void speedUp(int increment){
class in their own way. speed = speed + increment;
interface Vehicle { }
// all are the abstract methods. public void applyBrakes(int decrement){
void changeGear(int a); speed = speed - decrement;
void speedUp(int a); }
void applyBrakes(int a);
} public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}
}
class Bike implements Vehicle { Public class IntDemo {
int speed; public static void main (String[] args) {
int gear; Bicycle b1 = new Bicycle();
public void changeGear(int newGear){ b1.changeGear(2);
gear = newGear; b1.speedUp(3);
} b1.applyBrakes(1);
public void speedUp(int increment){ System.out.println("Bicycle present state :");
speed = speed + increment; b1.printStates();
} Bike bike = new Bike();
public void applyBrakes(int decrement){ bike.changeGear(1);
speed = speed - decrement; bike.speedUp(4);
} bike.applyBrakes(3);
public void printStates() { System.out.println("Bike present state :");
System.out.println("speed: " + speed bike.printStates();
+ " gear: " + gear); }
} }
}
Introduction to Packages
-Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are containers for classes. They are used to keep the class name space compartmentalized.
-Packages are stored in hierarchical manner and are explicitly imported into new class definitions.
-Package in java can be categorized in two form, built-in package and user-defined package.
1. Built-in Packages
These packages consist of a large number of classes which are a part of Java API. Some of the commonly
used built-in packages are:
-java.lang: Contains language support classes (Integer, Throwable, Thread etc). This package is
automatically imported.
-java.io: Contains classed for supporting input / output operations.
-java.util: Contains utility classes which implement data structures like Scanner, Collections, Date,
StringTokenizer etc.
-java.applet: Contains classes for creating Applets.
-java.awt: Contain classes for implementing the components for graphical user interfaces (like buttons,
labels, lists, menus etc)
2. User-defined packages
These are the packages that are defined by the user.
Advantages of Java Packages
Java package is used to categorize the classes and interfaces so that they can be easily maintained.
A package is container of a group of related classes where some of the classes are accessible are
exposed and others are kept for internal purpose.
• We can reuse existing classes from the packages as many times as we need it in our program.