UNIT-2
CONCEPTS OF INHERITANCE ,OVERRIDING, INTERFACES AND PACKAGES
2.1 Explain inheritance with an example program:
Inheritance:
• The process of deriving a new class from an already existing class is called “inheritance”.
• In object oriented programming the concept of inheritance provides the idea of reusability. This
means we can add additional features to an existing class without modifying it.
• We can derive a new class from existing class and add new features to it.
• The new class will have the combined features of both these classes
• The old class is known as base class (or) parent class (or) super class.
• The new class is called as derived class (or) child class (or) sub class.
Types of inheritance:
Inheritance is categorized into the following types
1. Single Inheritance: The process of deriving a new class from only one base class is called single
inheritance.
Base class
Derived class
2. Multiple Inheritances: The process of deriving a new class from more than one base class
is called multiple inheritance.
Base class1 Baseclass2
Base class2 Base class3
Derived class
3. Hierarchical Inheritance: The process of deriving more than one derived classes from the same
base class is called hierarchical inheritance.
Base class
Derivedclass1 Derivedclass2 Derivedclass3
4. Multilevel Inheritance: The process of deriving a new class from already derived class is called
multilevel inheritance. Base class
Derived class also acts as base class for derived class
Derived class
[Link] Inheritance: The process of deriving a new class involving more than one form of
inheritance is called as hybrid inheritance.
Syntax for inheritance: The general form of class declaration that inherits a super class is as follows:
Syntax: class subclassname extends superclassname
{
Variable declaration;
Method declaration;
}
Ex: class B extends A
{
The keyword „extends‟ tells that the properties of super class are extended into the sub class. The sub
class will contain own variables and methods as well as variables and methods of super class.
//program on single inheritance:
class A
{
int a,b;
void msg()
{
[Link](“the value of a=”+a +”and b=”+b);
}
class B extends A
{
int c;
void sum()
{
2
c=a+b;
[Link](c);
class SingleInheritance
{
public static void main(String args[])
{
B obj=new B();
obj.a=10;
obj.b=20;
[Link]();
[Link]()
}
2.2 illustrate how to implement multilevel inheritance with example program:
Multilevel inheritance:
In simple inheritance a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance a subclass is derived from a derived class. One class inherits only single class.
Therefore, in multilevel inheritance, every time ladder increases by one. The lower most class will
have the properties of all the super classes‟.
program on Multi level inheritance:
class Car{
public Car()
{
[Link]("Class Car");
}
public void vehicleType()
{
[Link]("Vehicle Type: Car");
}
}
class Maruti extends Car{
public Maruti()
{
[Link]("Class Maruti");
}
public void brand()
{
[Link]("Brand: Maruti");
}
public void speed()
{
[Link]("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti{
public Maruti800()
3
{
[Link]("Maruti Model: 800");
}
public void speed()
{
[Link]("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
[Link]();
[Link]();
[Link]();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph
2.3 Explain method overriding and usage of super keyword:
Method overriding: A method in a subclass has the same name, same arguments and same return
type as a method in the super class, then the method in the subclass is said to be override the method in
the super class.
(OR)
The process of redefining the original method into various derived classes for performing various
operations is known as method overriding
Ex:
class A
{
int a;
void display(int x)
{
[Link](“this is super class”);
[Link](“value of a is” +a);
class B extends A
{
int b;
void display(int x)
4
{
[Link](“this is sub class”);
[Link](“value of b is” +b);
class override
{
public static void main(String args[])
{
B obj=new B();
[Link](10);
} }
Output:
this is sub class
10
Super: The usage of keyword “super” in inheritance:
• Whenever we inherit the base class features into derived class, there is a possibility that base class
features are similar to derived class features. So that there is a possibility of getting confusion by the
JVM.
• In order to differentiate the base class features with derived class features, the base class features
must be preceded by a keyword „super‟ in the context of derived class.
•Super keyword can be used in three places:
1) super can be used to refer to super class variables, as:
[Link];
2) super can be used to refer to super class methods, as:
[Link]();
3) super can be used to refer to super class constructor , as:
super(values);
super() must always be first statement executed inside a sub class constructor
Example Program:
Ex:
class A
{
int a=10;
void display()
{
5
[Link](“this is super class”);
[Link](“value of a is” +a);
class B extends A
{
int b=20;
void display()
{
[Link](); //calling super class show
[Link](“this is sub class”);
[Link](“value of b is” +b);
}
}
class override
{
public static void main(String args[])
{
B obj=new B();
[Link]();
} }
Output:
this is super class
10
this is sub class
20
2.4 Describe concept of interfaces:
Define interface:
➢ An interface in java is a blueprint of a class. It has static constants and abstract methods only.
➢ The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods
in the java interface not method body.
➢ It is used to achieve fully abstraction and multiple inheritances in Java.
➢ Java Interface also represents IS-A relationship.
6
➢ It cannot be instantiated just like abstract class.
Interface Syntax:
Access-specifier interface <interface-name>
{
Declaration of variables;
Declaration of methods;// no definition
}
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve fully abstraction.
o By interface, we can support the functionality of multiple inheritances.
o It can be used to achieve loose coupling.
Interface fields are public, static and final by
default, and methods are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class.
interface printable
void print();
7
class A implements printable
public void print1()
[Link]("Hello");
}
Class B {
public static void main(String args[])
{ A obj = new A();
obj.print1();
}
Output : Hello
2.5 Difference between abstract class and interface:
8
2.6 Explain implementation of interface with example:
Once an interface has been defined, one or more classes can implement that interface. To implement an interface,
include the “implements” clause in a class definition & then create the methods defined by the interface.
The general form of a class to implement an interface:
class classname implements interface1,
interface2………
// class body
}
e.g: class Use implements printable
{
public void print1()
{
[Link](“hello”);
}
Multiple Inheritance using Interfaces:In multiple inheritance, sub classes are derived from multiple super classes. By
using multiple interfaces we can achieve multiple inheritances. Let us take 2- interfaces as:
interface Printable
int a=10;
void print1();
interface Showable
int b=20;
void show();
class A7 implements Printable,Showable
9
{
public void print1()
[Link]("printable a="+a);
}
public void show()
[Link]("showable b="+b);
}
class Multiple
{
public static void main(String args[])
A7 obj = new A7();
obj.print1();
[Link]();
}
Extending interfaces: One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes.
When a class implements an interface that inherits another interface, it must provide implementation of all
methods defined within the interface inheritance.
Note: Any class that implements an interface must implement all methods defined by that interface, including
any that inherited from other interfaces.
interface f1
{
void disp1();
}
interface f2 extends f1
{
void disp2();
}
class A implements f2
10
{
public void disp1()
{
[Link]("This is display of i1");
}
public void disp2()
{
[Link]("This is display of i2");
}
public class Ext_iface
{
public static void main(String args[])
{
A obj = new A();
obj.disp1();
obj.disp2();
}
Output: This is display of i1
This is display of i2
THE SCOPE OF VARIABLES IN INTERFACES
➢ Interfaces can be used to declare a set of shared constants that can be used in different classes.
➢ This is similar to creating header files in C/C++ to contain a large number of constants.
➢ The constant values will be available to any class that implements the interfaces.
➢ Once declare any variable inside the interface these variables use inside package and outside
package also because these members are public by default
Example:
interface A
{
int a=50;
float b=30.8;
}
class B implements A
{
int len=a;
public float calculate()
{
11
return(len*b);
}}
Class C
{
public static void main(String args[])
{
B b=new B():
[Link](“Result=” +([Link]()));
}}
2.7 Define packages:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two forms,
1. Built-in package and
2. User-defined package.
1. Java Built-in package (or) Java API packages (or) Java system packages: Java API [Application
Programming Interface] provides a large no. of classes grouped into different packages according to
functionality.
Java
Frequently used java built-in packages are
Package Contents
name
[Link] Language support classes. These are classes that java compiler
itself uses and therefore they are automatically imported. They
include classes for
primitive types, strings, math functions, threads and exceptions.
[Link] Language utility classes such as vectors, Hash tables, random
numbers ,
date, etc.
[Link] Input / output support classes. They provide facilities for the
input and
output of data.
[Link] Set of classes for implementing graphical user interface. They include
classes
for windows, buttons, lists, menus and so on.
12
[Link] Classes for networking. They include classes for communicating
with local
computers as well as with internet servers.
[Link] Classes for creating and implementing applets.
2. User defined packages: we can define our own packages. These user defined packages are created as
follows:
We must first declare the name of the package using the ‘package’ keyword followed by a
package name then we define a class as public, just as we normally define a class.
package packagename; // package declaration
public class classname // class definition
{
• Here the package name is name of the package.
• The class name is the name of the class.
CREATING PACKAGES: Creating our own package involves the following steps:
[Link] the package at the beginning of file using the form
package packagename;
[Link] the class that is to be put in the package and declare it public.
[Link] a subdirectory under the directory where the main source files are stored.
[Link] the .java file in the subdirectory created.
[Link] the .java file and this creates .class file in the subdirectory.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
2.8 Explain the concept of class path:
CLASS PATH: the CLASS PATH is an environmental variable that tells the java compiler where to
look for class files to import. CLASS PATH is generally set a directory.
To set the CLASS PATH, the procedure is:
1. Right click on my computer
2. Select system properties. The system properties dialog box will appears.
3. In this select advanced tab & then click on environmental variables button
4. Go to user variables & click on New button
5. Type the following:
Variable name: path
13
Variable value: c:\program files\java\jdk1.5.0\bin;
6. Then click on ok button
7. Then click on ok button in the environmental variables window and system properties window
C:\>set path=” c:\program files\java\jdk1.5.0\bin”;
C:\>set classpath=” c:\program files\java\jdk1.5.0\bin”;
After this, class files will be available anywhere in that computer system. Our program which uses the
package may present in any directory, it can be compiled and run without any problem
2.9 Describe concept of Access protection/ Access modifiers:
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specify accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1. private 2. default 3. protected 4. public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc. Here, we will learn access modifiers.
Understanding all java access modifiers
Let's understand the access modifiers by a simple table.
Modifier With in class Within package Outside Outside
package by sub package
class only
Private Yes No No No
Default Yes Yes No No
Protected Yes Yes Yes No
Public Yes Yes Yes Yes
1) Private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and
private method. We are accessing these private members from outside the class, so there is compile
time error.
//save by [Link]
class A
{
private int data=40;
private void msg()
{
[Link]("Hello java");
public class Simple
14
{
public static void main(String args[])
{
A obj=new A();
[Link]([Link]);//Compile Time Error
[Link]();//Compile Time Error
}
2) Default access modifier
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package.
Example of default access modifier
In this example, we have created two packages p1. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.
//save by [Link]
package p1;
class A{
void msg()
{
[Link]("Hello");
}
//save by [Link]
import p1.*;
class B {
public static void main(String args[]) {
A obj = new A();//Compile Time Error
[Link]();//Compile Time Error
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
3) Protected access modifier
The protected access modifier is accessible within package and outside the package but through
inheritance only.
15
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
Example of protected access modifier
In this example, we have created the two packages p1. The A class of p1 package is public, so can be accessed
from outside the package. But msg method of this package is declared as protected, so it can be accessed
from outside the class only through inheritance.
//save by [Link]
package p1; public
class A
protected void msg()
[Link]("Hello");
//save by [Link] import
p1.A; class B extends A
public static void main(String args[])
B obj = new B(); [Link]();
Output: Hello
4) Public access modifier
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
//save by [Link]
package p1;
public class A {
public void msg()
{
16
[Link]("Hello");
}
//save by [Link]
import p1.*;
class B {
public static void main(String args[]){
A obj = new A();
[Link]();
}
2.10 illustrate the mechanim of importing packages.
Importing packages (Accessing packages):
The import statement can be used to search a list of packages for a particular class.
The general form of import statement for searching a class is as follows:
Syntax: import package1[.package2][.package3].classname;
In the above syntax package1 is the name of the top level package, package2 is the name of the
package that is inside the package1, and so on. We can have any number of packages in a package
hierarchy. Finally the class name is specified.
Rules for importing packages:
1. The import statement must end with a semicolon.
2. The import statement should appear before any class definition in a sourced file.
3. Multiple import statements are allowed.
There are three ways to access the package from outside the package.
1. import package.*;
[Link] [Link];
[Link] qualified name.
17
//save by [Link] in p1 package
package p1;
public class B
{
public void display()
{
[Link]("HOW ARE YOU");
}
//save by [Link]
import p1.*;
class C {
public static void main(String args[]) {
A obj = new A();
B obj1=new B();
[Link]();
[Link]();
Output: Hello
HOW ARE YOU
18
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
Example of package by import [Link]
//save by [Link]
package p1;
public class A
public void msg()
{
[Link]("Hello");
}
//save by [Link]
import p1.A;
class C
public static void main(String args[])
{
A obj = new A();
[Link]();
}
3)Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the class or
interface.
It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.
Example of package by import fully qualified name
//save by [Link] in p1 package
package p1;
public class A
{
19
public void msg()
[Link]("Hello");
}
//save by [Link] in p2 package
package p2;
public class A {
public void show()
{
[Link](“How ARE U”);
//save by [Link]
Class C
Public static void main(String args[])
p1.A obj = new p1.A();//using fully qualified name
p2.A obj1=new p2.A();//using fully qualified name [Link]();
[Link]();
}
Output:Hello
HOW ARE YOU
To Compile p1 class: javac -d . [Link]
To compile current package class: javac [Link]
To run program: java C
2.11 Develop simple application to design packages with sample program:
//save [Link] file
package robo;
public class Add
20
int x,y;
public Add()
x=100;
y=200;
public void sum()
[Link]("Addition of two no's="+(x+y));
//save [Link]
import [Link];
class sana
public static void main(String args[])
Add obj=new Add();
[Link]();
Step1:
[Link] one folder in Localdisk( c)
[Link] name is Demo
[Link] open Demo folder and create new Folder in Demo
4. Folder name is robo( robo is a package name)
Step 2:
1. create a package( package name is robo,add is class name) and save [Link] file in rodo folder
21
2. next create main class and save [Link]( main class is sana) in demo folder
[Link] next go to command prompt
• c:\user\ADMIN>cd\
• c:\> cd Demo
• c:\Demo>cd robo
• c:\Demo\robo> javac [Link]
• c:\Demo\robo>cd..
• c:\Demo> javac [Link]
• c:\Demo>java sana
• Addition of two no's=300 //output
• C:\Demo>
------------- Prepared By [Link] -------------
22