Unit4 - Inheritance Packages Interfaces
Unit4 - Inheritance Packages Interfaces
INHERITANCE, PACKAGES
AND INTERFACES
TOPIC TO BE COVERED…..
4.1Basics of Inheritance:
Types of inheritance
concepts of method overriding,
extending class, super class, subclass,
dynamic method dispatch & Object class
4.2 Creating package, importing package, access
rules for packages, class hiding rules in a
package
4.3Defining interface, inheritance on interfaces,
implementing interface, multiple inheritance
using interface
4.4 Abstract class and final class
INHERITANCE
It is process by which objects of one class can use
properties of objects of another class.
The mechanism of deriving a new class from old
class is called inheritance.
Data Data
methods methods
object object
class A class B
INHERITANCE
Inheritance provides reusability of code.
Java class can be reused in several ways by creating
new class.
Reusing the properties of existing class called
inheritance.
Old class is also known as
Base class
Super class
Parent class
New class is also known as
Derived class
Sub class
Child class
INHERITANCE
Inheritance allows subclasses to inherit all variable
and methods of their parent class.
Object have no super class.
Types of inheritance :
1) Single inheritance (only one super class)
2) Hierarchical inheritance(1 super class, many
subclasses)
3) Multilevel inheritance (derived from a derived
class)
4) Multiple inheritance(several super class)
5) Hybrid inheritance(more than one super and sub
class)
[ Java does not directly support multiple inheritance
which is actually supported in c ++, but it is
implemented using interface.]
Syntax for defining a subclass:
class A
{ A
---------
---------
}
class B extends A B
{
--------- Single inheritance
---------
}
EXAMPLE
class A //super class
{
int i;
}
class B extends A //sub class
{
void display()
{
System.out.println("i="+i);
}
}
EXAMPLE
class Single
{
public static void main(String args[])
{
B b1=new B();
b1.i=7;
b1.display();
}
}
Output:
i=7
MULTI LEVEL INHERITANCE
New class is derived from derived class.
Java uses mainly in building its class library
Class C members
A Super class
Class B members
Class A members
B Intermediate super class
C Sub class
Multilevel inheritance
class A
{
---------
---------
}
class B extends A
{
---------
---------
}
class C extends B
{
---------
---------
}
Here class C can use properties of class B and class B uses the
properties of class A. So class C can use properties of A and B.
HIERARCHICAL INHERITANCE
one super class, many subclasses.
Many classes extends one sub class
B C D
Multilevel inheritance
class A
{
---------
}
class B extends A
{
---------
}
class C extends A
{
---------
}
Class D extends A
{
---------
}
Here, class A extended by class B ,C, D.
MULTIPLE INHERITANCE
One class extends properties of Several super classes.
Java does not support this directly.
A B
multiple inheritance
class HybridDemo
{
public static void main(String args[])
{
D obj1= new D();
obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
NESTING METHODS
A method can be called by using only its name by
another method of same class, is nesting of methods.
class Nesting
{ int m,n;
Nesting(int x , int y)
{ m=x; n=y;
}
int largest ( )
{ if( m >= n)
return(m);
else
return(n);
}
EXAMPLE
void display ( )
{
int large=largest ( ); //calling a method
System .out. println (“large value”+large);
}}
class Nest_test
{
public static void main(String args[ ])
{
Nesting n=new Nesting ( 50 , 40 );
n .display ( );
}
} output : 50
SUB CLASS CONSTRUCTOR
Constructor which is defined in subclass is called sub
class constructor.
It is used to create instance variable of both sub class
and super class.
super keyword is used.
class B extends A
{ int i;
B ( int a , int b)
{ super . i =a;
i =b; }
void show( )
{
System . out .println ( “i in super =“ +super .i ) ;
System . out .println( “i in sub =“ +i); }
}
EXAMPLE
class SuperDemo
{
public static void main ( String args[ ])
{
B subob= new B( 1, 2);
subob . show();
}
}
Output:
i in super=1
i in sub=2
METHOD OVERRIDING
(FUNCTION OVERRIDING)
Methods defined in super class is inherited and used
by objects of the subclass .
If we want an object to respond to same method but
having different behavior when method is called .
It is possible by defining a method in sub class ,that
has same name , same arguments, same return
type as in method in the super class.
When method in super class is called ,the method
define in subclass is invoked and executed instead of
one in super class this is called overriding of method.
METHOD OVERRIDING
(FUNCTION OVERRIDING)
When same method name , same argument &
same return type) is used in sub class and super
class ,is called method overriding.
We can overload methods in same class.
In this case, Method in sub class overrides the
method in super class.
Note:
1. Method overloading can be done in same
class.
2. Method overriding can be done in different
class. when super class and subclass are used(
when inheritance is used).
EXAMPLE
class SuperClass
{
void display( )
{
System .out .println ( “ Super Class”);
}
Sub class
Sub class
x in sub class= 5
EXAMPLE 2:
class Super
{
int x;
Super (int x)
{
this.x =x;
}
void display( )
{
System .out .println (“super x=“+x);
}
}
class Sub extends Super
{
int y=10;
Sub (int x ,int y)
{ super( x);
this . y =y; // if put this statement in comment
line, y has value 10.
}
void display( )
{
System .out .println (“super x=“+x);
System .out .println (“sub y=“+y);
}
}
class Override
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
s1.display();
}
}
ABSTRACT CLASS AND METHODS
final makes any method protected means it cant be
extended. Java also allow us to exactly opposite to above
one.
If we want method must always be redefined in subclass
,to make overriding compulsory.
Then abstract (modifier) keyword is used to make
overriding compulsory.
abstract can be used with class and methods.
static
Non-static
Nested class are particularly helpful in handling
events in applets.
class A
Outer class
// can’t access member of or
Enclosing class
B
class B
//outobj. display ( );
}
}
STATIC NESTED CLASS & NON-
STATIC NESTED CLASS
Static nested class:
Class has static modifier specified.
{
Sum s=new Sum( );
int total=s . sumn( 5) ;
System . out .println( “sum of 1 to 5=” + total);
}
}
RETURNING OBJECTS
A method can return any type of data including class
type (object ) ,which is created by user.
In this example, each time incrByTen( ) is invoked ,a
new object is created and a reference to it is returned
to calling routine.
EXAMPLE
class Test
{
int a;
Test ( int i)
{
a=i ;
}
Test incrByTen( )
{
Test temp= new Test (a+10 );
return temp;
}}
EXAMPLE
class Return_obj
{
public static void main (String args[ ] )
{
Test obj1=new Test( 2 );
Test obj2;
obj2=obj1.incrByTen( );
System . out . println( “obj1.a=“ + obj1.a );
System . out . println( “obj2.a=“ + obj2.a );
obj2=obj2.incrByTen ( );
System . out . println( “obj2.a after second increase“ +
obj2.a );
}}
EXAMPLE
Output:
Obj1.a=2
Obj2.a=12
Obj2.a after second increment =22
INTERFACE :MULTIPLE INHERITANCE
Ex:
class C extends B,A
It is not
{ permitted
in Java.
---------
}
INTERFACE :MULTIPLE INHERITANCE
But large number of real life applications require
the use of multiple inheritance where we can
inherit methods and properties from several
distinct classes.
Interface defines :
Note:
All variables are declared as constants.
class B B C
interface C
implements class A D interface
class D extension extension
class B E interface
implementation
extension
class C
EXAMPLE
interface Area //interface defined
{
final static float PI=3.14F;
float compute(float x, float y);
}
// interface implemented
class Rectangle implements Area
{
public float compute ( float x , float y)
{
return (x * y);
}}
EXAMPLE
class InterfaceTest
{
public static void main(String args[ ])
{
// class object
Rectangle rect = new Rectangle ( );
// interface object
Area a ;
a = rect ;
System.out.println ( “Area of rectangle =“ +
a. compute(10,20));
}}
INTRODUCTION TO PACKAGE
OOP’s main feature is its ability to reuse the code
which is already created.
If we want to use classes from other programs
without physically copying them into program under
development ,then packages are used.
What is package?
Packages are grouping of variety of classes and/or
Interfaces together.
Packages are conceptually similar as “class libraries
“ of other languages.
Packages act as “containers” for classes.
TYPES OF PACKAGE
Java packages are classified into two types
1) Java API packages
There are six API available in java which is
System defined Package.
2) user defined packages
In java we can create our on package based on
the requirement of User.
BENEFITS OF USING PACKAGES
The classes contained in the packages of other
program can be easily reused.
In packages ,classes can be unique compared with
classes in other packages. means two classes in two
different packages can have the same name.
Packages provide a way to “hide “ classes thus
preventing other programs or packages from
accessing.
Package also provide a way of separating designing
from coding. It is possible to change implementation
of any method without affecting the rest of the
design.
JAVA API PACKAGE
JAVA SYSTEM PACKAGES AND THEIR
CLASSES
Package
Description
No name
1 java.lang Language support classes
These are classes that java compiler itself uses
and therefore they are automatically imported
They include classes for primitive types, math
functions ,threads and exceptions.
2 java.util •Language utility classes
It includes Vector ,hash tables, random
numbers.
3 java.io •Input/output support classes
They provide facilities for the input and
output of data
JAVA SYSTEM PACKAGES AND THEIR
CLASSES
Package
Description
No name
4 java.net •Network communication supporting
classes
Classes for communicating with local
computers as well as internet servers
5 java.awt Abstract window toolkit
•Set of classes for implementing
graphical user interface.
They include classes for windows ,buttons,
lists, menus and so on..
6 java.
Classes for creating and implementing
applet
applets.
HOW TO USE SYSTEM PACKAGES?
Two approaches are Used.
Syntax:
import
java.Packagename.classname;
or
import Packagename.*;
NAMING CONVENTION
Package should begin with lower case letter.
Every package name must be unique to make best
use of packages. Duplicate name will cause errors
on internet.
Java suggests to use domain name as prefix to
preferred package name.
E.g. :
college.student.mypackage
Where
college denotes college name
student denotes student name
CREATING PACKAGE
To create a package first declare the name of package
using package keyword.
Syntax: package packagename;
Example:
package firstPackage; //package declaration
public class First Class //class declaration
{
//body of class
}
Save file as FirstClass.java in directory firstPackage
Package1
(top level) package2
package3
Classname
Multiple import statements are allowed.
ACCESSING A PACKAGE
We can also use shortcut approach as follows:
import packagename .* ;
* indicates that the compiler should search this
entire package hierarchy when it encounters a class
name.
Drawback of that approach is that it is difficult to
determine from which package a particular member
came.
EXAMPLE
package package1;
public class ClassA
{
public void displayA()
{
System.out.println (“Class A”);
}}
/*source file should be named ClassA.java and stored in
subdirectory package1 and the resultant class
ClassA.class will be stored in same directory. */
e.g. : D:\javapro\package1\ClassA.java
EXAMPLE
import package1.classA;
class Packagetest
{
public static void main(String args[])
{
ClassA objA=new ClassA();
objA . displayA();
}}
In this ClassA imported from package1.
This code should be saved as Packagetest.java and then
compiled.
EXAMPLE
class PackageTest3
{
public static void main(String args[])
{
ClassC objc =new ClassC();
objc. displayB ();
objc. displayC ();
}
}
ACCESS PROTECTION
Access
Modifier Friendly Private
public protected Private
Access (default) protected
Location
Same class yes Yes yes Yes Yes
Subclass in
same package yes Yes Yes yes No
Other classes
in same Yes yes Yes No No
package
Subclass in
Yes Yes No Yes
Yes No
other packages
Non-subclasses
in other Yes No No No No
package
ADDING A CLASS TO A PACKAGE
1.Define the class and make it public
2.Place the package statement ------ package p1;
3.Store this file as B.java file under the directory
p1;
4.Compile B.java file. This will create B.class file
and place it in the directory p1.
Advanced tab
Environment variable
value=“c:\program files\java\jdk1.2\bin