[go: up one dir, main page]

0% found this document useful (0 votes)
21 views69 pages

Module2 - OOP - Inheritance, Packages and Interfaces

The document covers concepts of inheritance, packages, and interfaces in Java, including how to create arrays of objects and the principles of object-oriented programming (OOP). It explains various forms of inheritance such as single, multilevel, hierarchical, multiple, and hybrid inheritance, along with their syntax and examples. Additionally, it discusses method overriding, runtime polymorphism, and the use of the 'super' and 'this' keywords in class hierarchies.

Uploaded by

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

Module2 - OOP - Inheritance, Packages and Interfaces

The document covers concepts of inheritance, packages, and interfaces in Java, including how to create arrays of objects and the principles of object-oriented programming (OOP). It explains various forms of inheritance such as single, multilevel, hierarchical, multiple, and hybrid inheritance, along with their syntax and examples. Additionally, it discusses method overriding, runtime polymorphism, and the use of the 'super' and 'this' keywords in class hierarchies.

Uploaded by

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

Module2: Inheritance, Packages and

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();

for(int i=0; i< n ; i++)


if(s[i].avg >= p)
s[i].display();
}
}
2. Inheritance in Java
• Process of acquiring the properties and behaviors of one class to another class.
Properties: variables
Behaviors: methods
• When we inherit from an existing class, we can reuse methods & data of parent class; we can add
new methods and data also.
• Inheritance represents the IS-A relationship, also known as parent-child relationship.
• Need of inheritance in java
o For Method overriding (so runtime Polymorphism can be achieved).
o For Code Reusability(to reduce length of the code and redundancy)
o It allows creation of Hierarchical Classification.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields of sub class
}
The extends keyword indicates that we are making a new class that derives from an existing class.
Extends keyword provide relationship between two classes.
 A class which is inherited is called parent or super class or base class.
 The new class is called child or subclass or derived class.
 A subclass is a specialized version of a super class. It inherits the members defined by the super
class and adds its own unique elements.
 Inheritance represents the IS-A relationship, also called
Parent-Child relationship.
Eg: A Student Is-A Person, Programmer Is-A Employee

 Here Programmer is the subclass and Employee is the


super class.
Relationship between two classes is Programmer IS-A
Employee.
It means that Programmer is a type of Employee.
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
float bonus=(0.2)*salary;
}
public class InhDemo
{
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salay);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
} In the above example, Programmer object can access
Programmer salary is: 40000.0 the field of own class as well as of Employee class i.e.
Bonus of programmer is: 10000 code reusability.
Types of inheritance in java
there are three types of inheritance in java: single, multilevel, hierarchical, multiple and hydrid

1. Single Level Inheritance


A super class is inherited by only one
sub class.

2. Multi Level Inheritance


A sub-class will be inheriting parent
class and as well as, the sub-class act as
a parent class to other class., and so on.

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.

//Program to Demonstrate Single Inheritance public class SingleLevel


class ClassA {
{ public static void main(String args[])
public void showA() {
{ ClassB b = new ClassB();
System.out.println("show method of ClassA"); b.showA();
} b.showB();
} }
}
class ClassB extends ClassA
{
public void showB()
{
System.out.println("show method of ClassB");
}
}
Multi Level Inheritance: int k=20;
One sub class is extending parent class then that public void showC()
sub class will become parent class of next {
extending class. System.out.println(" value of C is "+k);
class A{ System.out.println("The members sum is " + (i +j
int i=10; +k));
public void showA() }
{ }
System.out.println(" value of A is "+i); public class MultiLevel
} {
} public static void main(String args[])
class B extends A{ {
int j=25; C c = new C();
public void showB() c.showA();
{ c.showB();
System.out.println(" value of B is "+j); c.showC();
} }
} }
Hierarchical Inheritance: class D extends A{
More than one sub class is extending single parent int j=55;
class public void showD() {
class A{ System.out.println("method of D"+j);
int i=10; }
public void showA() { }
System.out.println("method of A"+i); public class HierLevel{
}} public static void main(String args[]) {
class B extends A{
int j=25; B b = new B();
public void showB() { b.showA();
System.out.println(" method of B"+j); b.showB();
} C c = new C();
} c.showA();
class C extends A{ c.showC();
int j=99; }
public void showC() { }
System.out.println(" method of C"+j);
}
}
super keyword : Super keyword is used to represent super class object.
• Super class variables
• Super class methods
• Super class constructors
1. Calling of super class variables:-
class Test1
{
int a=10;
int b=20;
}
class Test extends Test1
{
int a=100;
int b=200;
void add(int a,int b) {
System.out.println(a+b);
System.out.println(this.a+this.b);
System.out.println(super.a+super.b);
}
public static void main(String[] args) {
Test t=new Test();
t.add(1000,2000);
}
}
2. Calling of super class methods:-
class Parent
{
void m1() {
System.out.println("parent class method");
}}

class Child extends Parent


{
void m1() {
System.out.println("child class method");
}
void m2() {
this.m1();
System.out.println("child class method");
super.m1();
}
public static void main(String[] args)
{
Child c=new Child();
c.m2();
}}
3. Calling of super class constructors:- Compilation error
No compilation error class Test1
class Test1 {
{ Test1(int i,int j)
Test1(int i,int j) {
{ System.out.println(i);
System.out.println(i); System.out.println(j);
System.out.println(j); System.out.println("two arg constructor");
System.out.println("two arg constructor"); }
} };
} class Test extends Test1
class Test extends Test1 {
{ Test(int i)
Test(int i) {
{ System.out.println("int -arg constructor");
super(100,200); super(100,200);
System.out.println("int -arg constructor"); }
} public static void main(String[] args) {
public static void main(String[] args) Test t=new Test(10);
{ }
Test t=new Test(10); }
}}
// Program to access super class constructor {
class Box width = height = depth = len;
{ }
private double width; double volume()
private double height; {
private double depth; return (width * height * depth);
Box(Box ob) }}
{ class BoxWeight extends Box
width = ob.width; {
height = ob.height; double weight;
depth = ob.depth; BoxWeight(BoxWeight ob)
} {
Box(double w, double h, double d) super(ob);
{ weight = ob.weight;
width = w; }
height = h; BoxWeight(double w, double h, double d, double m) {
depth = d; super(w, h, d); // call super class constructor
} weight = m;
Box() }
{ BoxWeight()
width = -1; {
height = -1; super();
depth = -1; weight = -1; }
}
BoxWeight(double len, double m)
{
super(len);
weight = m;
}
}
public class SuperDemo1
{
public static void main(String args[])
{
BoxWeight b1 = new BoxWeight(12,23.5);
BoxWeight b2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight b3 = new BoxWeight();
BoxWeight b4 = new BoxWeight(b2);
System.out.println(b1.volume() + “ : " +b1.weight);
System.out.println(b2.volume() + " : " +b2.weight);
System.out.println(b3.volume() + " : " +b3.weight);
System.out.println(b4.volume() + " : " +b4.weight);
}
}
// super() is provided by the compiler implicitly
class Animal
{ public class SuperDemo3
Animal() {
{ public static void main(String args[])
System.out.println("animal is created"); {
} Dog d=new Dog();
} }
class Dog extends Animal }
{ Output :
Dog() animal is created
{ // super(); calls automatically. dog is Created
System.out.println("dog is created");
}
}
/ demonstrate when constructors are called,
The order in which derived is order of constructor
execution
class A class C extends B
{ {
A() C()
{ {
System.out.println("Inside A's constructor."); System.out.println("Inside C's constructor.");
} }
} }
class B extends A public class SuperDemo4
{ {
B() public static void main(String args[])
{ {
// super() ; implicitly done by compiler C c = new C();
System.out.println("Inside B's constructor."); }
} }
} //output: order – A->B->C constructors
1. Create Objects for real world using Inheritance.
Problem Solving Assignment
1 Create a class hierarchy to demonstrate the following structure with appropriate data and methods.

2. Create a Multilevel Structure to demonstrate the following inheritance

Use super and this keyword appropriately.


Member Access and Inheritance
Although a subclass includes all of the members of
its superclass, it cannot access those members of
the superclass that have been declared as private.
public class AccessDemo {
class A { public static void main(String args[])
int i; {
private int j; // private to A B b1 = new B();
void setij(int x, int y) b1.setij(10, 12);
{ b1.sum();
i = x; System.out.println("Total is " + b1.total);
j = y; b1.i=20
} b1.j=24 //Compile Time Error
} }
class B extends A { }
int total;
void sum() {
total = i + j; // Compile time error
}
}
Use super and this keyword appropriately.
Method Overriding
 “when a method in a subclass has the same name and type signature as a method in its super class,
then the method in subclass is said to override the method in super class.”
 The subclass will hide the super class version.
 Method overriding occurs only when the name and type signature of two methods is identical.
 Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Note: If super class and sub class has the same method name but different signature (parameter
declarations), then the methods are overloaded but not overridden.

Rules for Method Overriding


o Method in sub class must have same name and parameter signature as super class.
o Must be Is-A relationship. (Inheritance).
o We cannot override a main () method because it is a static method belongs to class but not to heap

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

//Example to demonstrate final variable


final keyword with a method }
 A method declared as final, will not allow void display()
overriding. i.e. It prevents overriding / stops {
overriding. System.out.println("Honda's Show");
 A constructor cannot be declared as final. }
Because it is never inherited. }
 A final method is inherited, but not public class FinalDEmo2
overridden. {
class Bike public static void main(String args[])
{ {
final void show() Honda h1 = new Honda();
{ h1.display();
System.out.println("Bike's Method"); h1.show(); //compile time error
} }}
}
class Honda extends Bike
{ //inherits show()
void show()
{
System.out.println("Honda's Show");
final keyword with a class

If a class declared as final, it cannot be inherited i.e we cannot create sub class for that final class.

final class Bike


{
final void show()
{
System.out.println("Bike's Method");
}
}
class Honda extends Bike //Compile time error
{
//trying to inherit - CTE
}
Abstract class:
Any class that contains one or more abstract methods, then the class is defines as abstract class.
-An abstract method has no body defined in it.
-An abstract class is non-concrete class.
 Concrete class is a class that has an implementation for all of its methods. They cannot have any
unimplemented methods. It can also extend an abstract class or implement an interface as long as it
implements all their methods. It is a complete class and can be instantiated.
 Non-Concrete class is a class that has no implementation for some of the methods defined in it. It is
an incomplete class and cannot be instantiated.
abstract double area(double d1 , double d2); abstract double area( ); //abstract method
abstract void show();
abstract class Figure void display() // concrete method
{ {
double dim1,dim2; System.out.println(dim1);
Figure(double d1 , double d2) System.out.println(dim2);
{ }
dim1 = d1; }
dim2 =d2; }
Rules for abstract modifier
• Abstract class is declared with abstract keyword.
• Abstract class has one or more abstract methods.
• Abstract method has no method body.
• Abstract class can have instance variables, methods and abstract methods also.
• For the abstract classes it is not possible to create an object. Because it contains the
unimplemented methods, but a reference can be created.
• Whenever an abstract class is created , subclass should be created to it and the abstract methods
should be implemented in the sub classes, then we can create objects to the subclass.
• Abstract class reference can be used to refer to objects of its subclasses. But abstract class reference
cannot refer to the individual methods of subclasses.
• Class cannot be both final and abstract.
//Example 1: To demonstrate abstract class.
abstract class A
{
abstract void show (); public class AbstractDemo1
public void display() {
{ public static void main(String args[])
System.out.println("This is non abstract {
method"); // A a = new A(); // Compile time error
} B b = new B();
} b.show();
class B extends A b.display();
{ }
void show() //implements abstract method }
{
System.out.println("Abstract method”);
}
}
//Example 2 : To demonstrate abstract class. {
abstract class Figure Rectangl(double a, double b)
{ {
double dim1; super(a, b); }
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
abstract double area(); //abstract method {
public void display() Triangle(double a, double b)
{ {
System.out.println("The dimensions are"); super(a, b); }
System.out.println(dim1); double area()
System.out.println(dim2); {
} System.out.println("Inside Area for Triangle.");
} return dim1 * dim2 / 2;
}}
public class AbstractDemo2
{
public static void main(String args[])
{
Figure f = new Figure(10, 10); //CTE
Rectangl r = new Rectangl(9, 5);
Triangle t = new Triangle(10, 8);
Figure ref;
ref = r; //upcasting
ref.display();
System.out.println("Area of Rectangle is " + ref.area());
ref = t;
ref.display();
System.out.println("Area of Triangle is " + ref.area());
}
}
//Example 3: To demonstrate abstract class. class AbstractDemo3
abstract class Bank {
{ public static void main(String args[])
abstract int getRateOfInterest(); {
} Bank b;
class SBI extends Bank b=new SBI();
{ System.out.println("Rate of Interest is:
int getRateOfInterest() "+b.getRateOfInterest());
{ b=new PNB();
return 7; System.out.println("RateofInterest is:
} "+b.getRateOfInterest());
} }
class PNB extends Bank }
{
int getRateOfInterest()
{
return 8;
}
}
2. Interfaces
 An Interface allows creating a fully abstract class.
 An interface specifies what a class must do but not how it does it.
 An Interface has
o Methods declared without any body
o Final and static data members. (No Instance variables).
 Once an interface is defined, any number of classes can implement an interface.
 The class which implements an interface must provide definition for all the methods of an interface.
 The keyword interface allows defining an interface.
 The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in
the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.
1. Interface is also one of the type of class it contains only abstract methods.
2. For the interfaces also .class files will be generated.
3. Each and every interface by default abstract hence it is not possible to create an object.
4. Interfaces not alternative for abstract class it is extension for abstract classes.
5. 100 % pure abstract class is called interface.
6. The Interface contains only abstract methods means unimplemented methods.
7. Interfaces giving the information about the functionalities it are not giving the information
about internal implementation.
8. To provide implementation for abstract methods we have to take separate class that class
we can called it as implementation class for that interface.
9. Interface can be implemented by using implements keyword.
10. For the interfaces also the inheritance concept is applicable.
Defining an Interface
access interface InterfaceName
{ Eg: interface IntDemo
return_type methodName1(parameters list); {
return_type methodName2(parameters list); void callme(int x);
------------------------------- }
return_type methodNamen(parameters list); Implementing Interfaces
type final_val_1 = value; To implement an interface, use “implements”
type final_val_2 = value; clause in the class definition and provide definition
------------------------------ for all the methods defined by the interface.
type final_val_n = value; access ClassName implements interface1 ,
} interface2
 All methods and variables are implicitly public {
and abstract. -----------------
 All variables are implicitly final and static, must Class body //implementation of methods
be initialized. -----------------
}
The type signature of implementing class must
match with the interface defined methods. Accessing Implementation through Interface
Eg: class Demo implements IntDemo references
{ class Test
public void callme(int x) {
{ public static void main(String args[])
System.out.println(“The Interface method {
implemented”); IntDemo i = new Demo();
System.out.println(“The value is “+x); i.callme();
} /* using class instance
} Demo d = new Demo();
d.callme(); */
}
}
// Example to demonstrate an interface.
interface Bank class IntDemo2
{ {
float rateOfInterest(); public static void main(String[] args)
} {
class SBI implements Bank Bank b=new SBI();
{ System.out.println("ROI: "+b.rateOfInterest());
public float rateOfInterest() }
{ }
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
interface it1 System.out.println ("m2-method
{ implementation");
void m1(); }
void m2(); public void m3()
void m3(); {
} System.out.println ("m3 –method
abstract class ImplClass implements it1 implementation");
{ }
public void m1() public static void main(String[] args)
{ {
System.out.println("m1-method Test t=new Test();
implementation"); t.m1();
} t.m2();
} t.m3();
class Test extends ImplClass }
{ }
public void m2()
{
Variable in Interfaces case 1 : c=a+b;
 By default the variables declared in interface are System.out.println("add " +c);
public static final. break;
 Variable are used in an interface to import case 2 : c=a-b;
Shared Constants into multiple classes. System.out.println("sub " +c);
 All variables of an interface must be initialized break;
before to use. case 3 : c=a*b;
//interfaces with shared variables System.out.println("mul " +c);
interface SharedData break;
{ }}
int ADD=1; public static void main(String[] args)
int SUB=2; {
int MUL=3; perform(ADD);
double PI=3.142; perform(SUB);
double SQRT2=1.414; } perform(MUL);
class IntDemo3 implements SharedData System.out.println("The SQRT of 2 is " +SQRT2);
{ System.out.println("The area of a circle is "+(PI * 4
static void perform( int ch) *4));
{ int a=20,b=5,c; }}
switch(ch)
Interfaces can be extended
 An interface can extend one or more other interfaces. Thus provides interface inheritance.
 A class which implements an interface must provide definition of all the methods of inheritance
chain.
 The inheritance with interfaces can be
1. Single level inheritance
2. Multi level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid Inheritance.
Eg: class SuperClass
{
void print()
{
System.out.println("Inside Super class");
}
}
// First Parent class
class A extends SuperClass
{
void print()
{
System.out.println("Inside Class A");
}
}
// Second Parent Class t.print(); //CTE - ambiguity
class B extends SuperClass }
{ }
void print()
{
System.out.println("Inside Class B");
}
}
// Error : Test is inheriting from multiple classes
class Test extends A, B
{
public static void main(String args[])
{
Test t = new Test();

However, it is supported in case of an interface because there is no ambiguity. It is because its


implementation is provided by the implementation class.
interface A
{
void print();
} Key points of Interfaces is
interface B  Blue Print of a class
{  Provides complete abstraction.
void print(); (100%)
}  Also represents Is-A relationship.
class MultiTest implements A,B  Cannot be instantiated. (Object
{ cannot be created)
public void print()  Used to achieve multiple inheritance.
{  By default all methods are public and
System.out.println("Allows Multiple inheritance"); abstract.
}  By default all data members are
public static void main(String args[]) static, final.
{ Eg: int a=10; is
MultiTest obj = new MultiTest(); public static final int a=10;
obj.print();
}
}
interface A {
}
Interface B {
}
class C implements A,B
{
//Implementation of A and B
}
 If there are two or more same methods in two interfaces and a class implements both interfaces;
Implementation is required only for one method.
 A class cannot implement two interfaces that have methods with same name but different return
type.
 Variable name conflicts can be resolved by interface name.

interface A class C implements A,B


{ {
int X=10; public static void main(String args[])
} {
Interface B System.out.println(X);
{ System.out.println(A.X);
int X=20; System.out.println(B.X);
} }
}
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.

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.

 Making searching/locating and usage of classes and interfaces easier


 Packages can be considered as data encapsulation (or data-hiding).
 Packages can be organized as hierarchical structures with sub packages and classes.
Defining a Package
-The “package” keyword is used to create a package in java.
-A package is defined using “package” command as the first statement in the java source file. Any class
defined with in this file belong to the specified package.
-The “package” statement defines a name space in which the classes are stored.
By default classes are put into a default package, which has no name.

The general form of package is


package pkgname;
Eg: package mypack;

Java uses file system directories to store the packages.


i.e. All .class files must be kept in a directory called mypack.
• More than one file can include the same package statement.
 We can create a hierarchy of packages. Thus forms multilevel package.
The “.” (period) Operator is used to create multilevel packages.
Eg: package com.vce.cse
 The directory structure is com/vce/cse to store “.class” files.
 Renaming a package is done after changing directory name only.
//Program to Demonstrate package
package mypack;
public class Calculator{
public int add(int a , int b) {
return(a+b);
}
public int sub(int a , int b) {
return(a-b);
}
public int mul(int a , int b) {
return(a*b);
}
public int div(int a , int b) {
return(a/b);
}
}
Calculator.class file is stored in mypack folder.
The form of “import” statement is
import pkg1.pkg2. .... (classname / *);
eg: import java.util.*; -> Entire Package
import java.util.Scanner; -> only a class from package
import java.util.ArrayList;
//Accessing a Package and Accessing Package
import mypack.*;
0r
import mypack.Calculator;
import mypack.Factorial;
public class PkgDemo{
public static void main(String args[]) {
Calculator c = new Calculator();
int x=10;
int y=20;
System.out.println("Addition" + c.add(x,y));
System.out.println("Multiplication" + c.mul(x,y));
Factorial f = new Factorial(6);
int res = f.fact();
System.out.println("The factorial is " +res);
}}
//Accessing a package with Fully Qualified Name
public class PkgDemo{
public static void main(String args[])
{
mypack.Calculator c = new mypack.Calculator();
int x=10;
int y=20;
System.out.println("Addition" + c.add(x,y));
System.out.println("Multiplication" + c.mul(x,y));
mypack.Factorial f = new mypack.Factorial(6);
int res = f.fact();
System.out.println("The factorial is " +res);
}
}
If we use “package.* “then all the classes and interfaces of it can be accessed but not its sub packages.
Finding Packages and classpath
1. By default, the Java runtime system uses the current working directory as its starting point for finding
package. i.e. If the package is sub directory of working directory , it will be found.
2. By specifying the directory path by setting the “classpath” environment variable.
Eg: classpath => d:/mypack;.;
3. We can use the –classpath option with java and javac to specify the path to classes.
Eg: e:/> set classpath=d:/mypack;.;
Access Protection in Java
Java provides many levels of protection to allow fine grained control over the visibility of variables,
methods within the classes, sub classes and packages.

Java provides four categories of visibility for class members.


1. Sub classes in the same package
2. Non sub classes in the same package
3. Sub classes in different packages
4. Classes that are neither in the same package nor sub classes.
Java Access Protection is implemented by using 4 levels of scope.
1. private
2. protected
3. no modifier
4. public
Creating Sub packages
//Creating sub package The Rectangl.class file stored in mypack/shape
package mypack.shape; directory.
public class Rectangl{ //Accessing sub package
public double len; import mypack.shape.*;
public double wid; or
public Rectangl(double x , double y) { import mypack.shape.Rectangl;
len=x; public class PkgDemo1
wid=y; {
} public static void main(String args[])
public double area() { {
return(len*wid); Rectangl r = new Rectangl(5,6);
} double res = r.area();
} System.out.println("Area is " +res);
}
}

You might also like