Chapter - 4 Inheritancepackageinterface
Chapter - 4 Inheritancepackageinterface
Chapter – 4 Inheritance,Packages,Interfaces
Inheritance is most important feature of object-oriented programming because it allows the creation of
hierarchical classifications.
Deriving new class from old class(existing class) is called inheritance.
Using inheritance, one object can get the properties of the other object.
we can create a general class, which contain common set of items. and other classes inherits() from that
general class and that inherited class can use properties of general class.
A class that is inherited is called a superclass(parentclass,baseclass). The class that is derived from the
superclass is called a subclass(childclass,derivedclass).
Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and
methods defined by the superclass and adds its own, unique elements.
Subclass can’t access the private members of its superclass directly.
purpose: 1. code reusability 2.To implement polymorphism
“extends” keyword is used to inherit a class.
class Box
{
int width;
int height;
void show1()
{
System.out.println(“value of width and height” + width + “ “ + height);
1
JAVA PROGRAMMING
}
}
class BoxWeight extends Box
{
int weight; // weight of box
void show2()
{
System.out.println(“value of weight” + weight);
}
void sum()
{
System.out.println(“sum=” +( width + height+weight));
}
}
class inheritance
{
public static void main(String args[])
{
Box b1=new Box();
BoxWeight b2 =new boxWeight();
b1.width=10;
b1.height=20;
System.out.println(“content of superclass”);
b1.show1();
b2.width=30;
b2.height=40;
b2.weight=50;
System.out.println(“content of subclass”);
b2.show1();
b2.show2();
b2.sum();
}
}
Output: content of superclass
value of width and height =10 20
content of subclass
value of width and height =30 40 50
sum=120
Superclass is general class which includes common features to all subclass of it.
subclass is derived from superclass,which inherits all of the instance variables and methods defined by the
superclass,and adds its own unique elements.
A subclass inherits variables and methods from its superclass and all of its ancestors but vice-versa is not
possible.
2
JAVA PROGRAMMING
(1) Singlelevel inheritance: Derived one class from another one class is called singlelevel inheritance
Class A
Class B
Ex:
Class A
{
void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class A method
3
JAVA PROGRAMMING
(2) Multilevel inheritance Derived one class from another derived class is called multilevel inheritance. In this
Class B is subclass for superclass A and Class B is superclass for class C.
Class A
Class B
Class C
Ex:
Class A
{
void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
void methodB()
{
System.out.println("Child class method");
}
Class C extends B
{
void methodC()
{
System.out.println("Child C class method");
}
4
JAVA PROGRAMMING
(3)Hierarchical inheritance: More than one classes are derived from one superclass is called hierarchical inheritance.
Class B
(4) Hybrid inheritance: It is the combination of more than one types of inheritance.
Polymorphism means in superclass and subclass, we have more than one method with same name and same
prototype. Which method will be called that will be decided at run time. This is called run time polymorphism.
When a method in a subclass has the same name and type signature(no. of arguments ) as a method in its
superclass, then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from subclass object, it will always refer to the version of that method
defined by the subclass. The version of the method defined by the superclass will be hidden.
A subclass cannot override a method that is declared as final or static in the super class.
Ex:
class A
{
void show()
{
System.out.println("superclass : ");
}
}
class B extends A
{
void show()
{
5
JAVA PROGRAMMING
super.show();
System.out.println("subclass: " );
}
}
class UseSuper
{
public static void main(String args[])
{
B b1 = new B();
b1.show();
}
}
Output: superclass:
subclass:
5.Explain super keyword with example.OR What are the uses of super in inheritance in Java.
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super.
super is used for two purposes.
1. super is used to access a member of the superclass that has been hidden by a member of a subclass.
2. super is used to call the superclass constructor.
1. super is used to access a member of the superclass that has been hidden by a member of a subclass.
If name of variable or method in superclass has the same name as in subclass then it can be accessed by super
keyword..
Syntax: super.member
member can either be an instance variable or method.
class super
{
String name;
}
class sub extends super
{
String name;
void detail()
{
super.name=”parent”;
name=”child”;
}
}
Ex:
class A
6
JAVA PROGRAMMING
{
int i=10;
void show()
{
System.out.println("i in superclass : " + i);
}
}
class B extends A
{
int i=20; // this i hides the i in A
void show()
{
super.show();
System.out.println("i in superclass : " +super. i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B b1 = new B();
b1.show();
}
}
Output: i in superclass: 10
i in superclass: 10
i in subclass: 20
A subclass can call a constructor method defined by its superclass by use of the super keyword
Syntax: super(parameter-list);
parameter-list specifies any parameters needed by the constructor in the superclass. super( ) must always be the
first statement executed inside a subclass constructor.
class A
{
int i,j;
A(int a,int b)
{
i = a;
j = b;
}
}
class B extends A
7
JAVA PROGRAMMING
{
int k;
B(int a, int b)
{
super(a,b);
k=0;
}
void show()
{
System.out.println(“i=”+i);
System.out.println(“j=”+j);
System.out.println(“k=”+k);
}
}
class UseSuper
{
public static void main(String args[])
{
B b1 = new B(1, 2);
b1.show();
}
}
Output: i =1
j =2
k=0
Dynamic method dispatch is the mechanism by which we can determined which an overridden method is
called at run time, rather than compile time. Dynamic method dispatch is the way to implements run-time
polymorphism.
In dynamic method dispatch,we create reference variable of superclass. This superclass reference variable can
refer to a subclass object.
When an overridden method is called through a superclass reference, Java determines which version of that
method to execute.
It determine based on which object is refered by Reference variable at the time the method call occurs and It
will execute a method of that object.
Thus, this determination is made at run time.
When different types of objects are referred to, different versions of an overridden method will be called.
Example:
class A
{
void show()
{
System.out.println("A's show method");
8
JAVA PROGRAMMING
}
}
class B extends A
{
void show()
{
System.out.println("B's show method");
}
}
class C extends A
{
void show()
{
System.out.println("C's show method");
}
}
class Dispatch
{
public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.show(); // calls A's version of show
r = b; // r refers to a B object
r.show(); // calls B's version of show
THE JAVA r = c; // r refers to a C object
r.show(); // calls C's version of show
}
}
Output: A’s show method
B’s show method
C’s show method
Sometimes we want that the superclass just declares the structure of the method without providing a complete
implementation of every method. Such classes are declared as abstract classes.
Abstract classes just declare the structure of the methods and it is the responsibility of the subclass to do
meaningful implementation of those methods.
Sometimes superclass is not able to implement the method declared in it. At this point we can declare this class
as abstract.
Method can also be abstract. The abstract method must be overridden by the subclass. To declare an abstract
method, use this general form:
9
JAVA PROGRAMMING
abstract class A
{
abstract void show() ;
void call()
{
System.out.println(“call method");
}
}
class B extends A
{
void show()
{
System.out.println("show method");
}
}
class abstract
{
public static void main(String args[])
{
B b = new B();
b.call();
b.show();
}
}
Output: call method
show method
There is one special class ,Object defined by Java.All other classes are subclasses of Object.The Object class is
the superclass for all classes in java. Because all the classes are derived from Object,the methods defined in
Object are shared by all classes.
A reference variable of type Object can refer to an object of any other class.
The Object class provides some common behaviors to all the objects.
10
JAVA PROGRAMMING
Object
Method Purpose
Class getClass() Obtains the class of an object at run time.
String tostring() Returns a string that describe the object.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize() called before an unused object is recycled.
EX:
class o1
{
public static void main(String args[])
{
o1 cal=new o1();
System.out.println(cal.getClass());
Integer i=new Integer(5);
System.out.println(i.getClass());
}
}
Output: class o1
class java.lang.Integer
o final variable:
In general we say “this cannot be changed” or “this is final”.
The final keyword specifies that the value of a variable is final and must not be changed.
it is same as “const” in c++.
we must initialize a final variable when it is declared.
variables declared as final do not occupy memory on per object basis.
final keyword can also be applied to methods.
Ex: final int cm_per_meter=100;
final float pi=3.14;
o final method:
We use method overriding in java.But sometimes we don’t want to use method overriding.To disallow a
method from being overridden,final keyword is used at the start of its declaration.
11
JAVA PROGRAMMING
o final class:
Sometimes we want to prevent a class from being inherited.
For this we declare a class as final.
Declare a class as final implicitly declares all of its methods as final.
Ex: final class A
{
…………..
}
class B extends A //error
{
………
}
10. What is package? What is the use of package? How you can create and run the package?
12
JAVA PROGRAMMING
Java uses file system directories to store packages. For example, if you have package MyPackage then the
.class files for any classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
More than one file can include the same package statement.
You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by
use of a period.
package p1;
public class A
{
public void showA()
{
System.out.println("I am A class of same package");
}
}
package p1;
public class B
{
public void showB()
{
System.out.println("I am B of same package");
}
}
Filename: ABC.java
package p1;
public class ABC
{
public static void main(String s[])
{
A a1=new A();
a1.showA();
B b1=new B();
b1.showB();
}
}
Output:
I am A class of same package
13
JAVA PROGRAMMING
All the built-in classes are stored in named packages in Java. Java includes the import statement to bring
certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only
its name.
In a Java source file, import statements occur immediately following the package statement if it exists and
before any class definitions.
Syntax:
import pkg1[.pkg2].(classname | *);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package inside the outer
package separated by a dot (.). Finally, you specify either an explicit classname or a star (*), which indicates
that the Java compiler should import the entire package.
EX:
import java.util.Date;
import java.io.*;
All of the standard Java classes included with Java are stored in a package called java. The basic language
functions are stored in a package inside of the java package called java.lang. It is implicitly (automatically)
imported by the compiler for all programs.
When a package is imported, only those items within the package declared as public will be available to non-
subclasses in the importing code.
package p1;
public class A
{
public void showA()
{
System.out.println("I am A class of same package");
}
}
Filename: C.java (Different package class)
package p2;
public class C
{
14
JAVA PROGRAMMING
Filename: ABC.java
package p1;
import p2.*;
public class ABC
{
public static void main(String s[])
{
A a1=new A();
a1.showA();
C c1=new C();
c1.showC();
System.out.println(c1.d);
}
}
Output:
I am A class of same package
I am C of different package
20
12. What is interface? How is it defined and implemented? Explain with example
Using keyword interface,you can fully abstract a class from its implementation.
It means , Interfaces are like classes, but they do not have instance variables, and their methods are declared
without any body. This means interfaces just declare what to do not how to do.
Interface is a keyword used to define a collection of method definitions and constant values .
once it is defined,any number of classes can implement an interface using “implements” keyword.one class can
implement any number of interfaces. To implement an interface, a class must create the complete set of
methods defined by the interface.
Java does not support multiple inheritance(we can inherit more than one class) directly instead java provides
interfaces.So through interface we can implement multiple inheritance.
Syntax for declaring interface:
15
JAVA PROGRAMMING
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
access:- is either public or not used. When it is declared as public, the interface can be used by any other code.
and the file must have the same name as the interface name in which it is declared.
interfacename:- is the name of the interface.
methods are just declared not defined. all methods and variables are implicitly public.
All the variables declared within the interface are final means can’t be modified.
interface add1
{
int c=30;
void sum(int a,int b);
}
step 2: implementing above interface in class.
class display implements add1
{
public void sum(int a,int b)
{
System.out.println(“sum is”+(a+b+c));
}
public static void main(String ars[])
{
display c1=new display();
c1.sum(10,20);
}
}
output: sum is =60
interface add1
16
JAVA PROGRAMMING
{
int c=30;
void sum(int a,int b);
}
interface add1
{
int c=30;
void sum(int a,int b);
}
interface mul1
{
int d=20;
17
JAVA PROGRAMMING
One interface can inherit from another interface by use of “extends” keyword.This is known as interface
inheritance.
when a class implements an interface which inherits another interface,it must provide implementation for all
methods defined within the interface inheritance chain.
interface add1
{
int c=30;
void sum(int a,int b);
}
interface mul1 extends add1 //this interface inherits all methods and variable of add1
{
void mul(int a,int b);
}
18
JAVA PROGRAMMING
GTU QUESTION:
19