Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

JAVA PROGRAMMING

Chapter – 4 Inheritance,Packages,Interfaces

1. Explain inheritance with example.


2. Define superclass and subclass.
3. Explain different types of inheritance.
4. What is polymorphism? Explain method overriding with example.
5. Explain super keyword with example.OR What are the uses of super in inheritance in Java.
6. Explain dynamic method dispatch with example.
7. Explain abstract classes with example.
8. Explain Object Class.
9. Explain final variable, final method and final class.
10. What is package? What is the use of package? How you can create and run the package?
11. Explain how can you import package.
12. What is interface? How is it defined and implemented? Explain with example.
13. Write a program to implement interface inheritance .
14. Write a program to implement multiple interface in one class.
15. Write a program to implement interface in more than one interface.

1. Explain inheritance with example.

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.

Syntax: class subclassname extends superclassname

Program: Here , Box is superclass Boxweight is subclass.

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

2. Define superclass and subclass.

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

subclass inherit those superclass members declared as public or protected.


A superclass can have any number of subclasses.
The subclass knows the properties and methods of its superclass but the superclass doesnot know about the
different properties and methods of subclasses.
subclass can not inherit the constructors from its superclass.

Base class Super class Parent class

Derived class Sub class Child class

3. Explain different types of inheritance.

Following are the types of inheritance.


1. single Inheritance
2. Multilevel Inheritance
3. Hierarchical inheritance
4. Hybrid inheritance

(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

obj.methodB(); //calling sub class B method


}
}

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

public static void main(String args[])


{
C obj = new C();
obj.methodA(); //calling super class A method
obj.methodB(); //calling subclass B method
obj.methodC(); //calling class C method
}
}

4
JAVA PROGRAMMING

(3)Hierarchical inheritance: More than one classes are derived from one superclass is called hierarchical inheritance.

Class B

Class C Class F Class D

(4) Hybrid inheritance: It is the combination of more than one types of inheritance.

4. What is polymorphism? Explain method overriding with example.

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

2. super is used to call the superclass constructor.

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

6. Explain dynamic method dispatch with example.

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

7. Explain abstract classes with example.

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

Syntax: abstract type name(parameter-list);


Any class that contains one or more abstract methods must also be declared abstract.
Syntax: abstract class classname
We can’t create the object of abstract class.
Also, you cannot declare abstract constructors, or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be
itself declared abstract.
EX:

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

8. Explain Object class.

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

Object defines the following methods.

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

9. Explain final keyword(final variable,method,class)

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

methods declared as final cannot be overridden.


Ex: class A
{
final void meth()
{
System.out.println(“this is final method”);
}
}
class B extends A
{
void meth() // error
{
System.out.println(“error”);
}
}

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?

Package is a container for classes.


Whenever you have many classes, each class must have unique name if they are in same name space means in
same package. If you store those classes into different packages then you can give two classes a same name.
Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
You can define classes inside a package that are not accessible by code outside that package.
You can also define class members that are only known to other members of the same package.
You can create a package by just including a package command as the first statement in a Java source file. Any
classes declared within that file will be the member of that specified package.
The package statement defines a name space in which classes are stored. If you omit the package statement, the
class names are put into the default package, which has no name.

Syntax: package packagename; OR package packg1.packg2.packg3;


EX : package MyPackage; OR package java.awt.image;

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.

Example: E:p1>A.java,B.java,ABC.java(In E drive foldername is p1)

Filename: A.java (Same package class)

package p1;
public class A
{
public void showA()
{
System.out.println("I am A class of same package");
}
}

Filename: B.java (Same package class)

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

I am B subclass of same package

Run: E:>p1>javac A.java


E:>p1>javac B.java
E:>javac p1/ABC.java
E:>java p1/ABC

11. Explain how can you import package.

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.

Filename: A.java (Same package class)

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

public int d=20;


public void showC()
{
System.out.println("I am C of different package");
}
}

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:

access interface interfacename


{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;

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.

Syntax for implementing interface:

class classname implements interfacename


{
classbody(implement or defines all the abstract methods of interface)
}
The methods that implement interface must be declared public.
Ex:
step 1: create interface

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

13. Write a program to implement interface in more than one class.

step 1: create interface

interface add1

16
JAVA PROGRAMMING

{
int c=30;
void sum(int a,int b);
}

step 2: implementing above interface in two class.


class display implements add1
{
public void sum(int a,int b)
{
System.out.println("sum is"+(a+b+c));
}
}
class display2 implements add1
{
public void sum(int a,int b)
{
System.out.println("mul is"+(a*b*c));
}
}
class abc
{
public static void main(String ars[])
{
display c1=new display();
c1.sum(10,20);
display2 c2=new display2();
c2.sum(10,20);
}
}
output: sum is =60
mul is =6000

14. Write a program to implement multiple interface in one class(multiple inheritance).

syntax: access classname implements interfacename1,interfacename2…


step 1: create interface

interface add1
{
int c=30;
void sum(int a,int b);
}
interface mul1
{
int d=20;

17
JAVA PROGRAMMING

void mul(int a,int b);


}

step 2: implementing multiple interface in one class.


class display implements add1,mul1
{
public void sum(int a,int b)
{
System.out.println("sum is"+(a+b+c));
}
public void mul(int a,int b)
{
System.out.println("mul is"+(a*b*c));
}
public static void main(String ars[])
{
display c1=new display();
c1.sum(10,20);
c1.mul(10,20);
}
}
output: sum is =60
mul is =6000

15. Write a program to implement interface inheritance .

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.

step 1: create interface

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

step 2: implementing interface in chain.


class display implements mul1 //implements add1 and mul1
{

18
JAVA PROGRAMMING

public void sum(int a,int b)


{
System.out.println(“sum is”+(a+b+c));
}
public void mul(int a,int b)
{
System.out.println(“mul is”+(a*b*c));
}
public static void main(String ars[])
{
display c1=new display();
c1.sum(10,20);
c1.mul(10,20);
}
}

output: sum is =60


mul is =6000

GTU QUESTION:

1. State the name of any four inbuilt Java package.


2. List four types of inheritance.
3. Explain Interface concept with example
4. Explain concept of user defined package in brief
5. Write a program to explain interface implementation.

19

You might also like