0% found this document useful (0 votes)
125 views

Inheritance, Interface and Package

The document discusses various object-oriented programming concepts in Java including inheritance, interfaces, packages, and polymorphism. It provides examples to illustrate single inheritance, multilevel inheritance, method overloading, constructor overloading, and access modifiers like public, private and protected. It contains 8 questions asking to write programs demonstrating these concepts through problems involving defining classes for employees, rectangles, boxes, persons etc and performing tasks like calculating areas, volumes, salaries etc.

Uploaded by

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

Inheritance, Interface and Package

The document discusses various object-oriented programming concepts in Java including inheritance, interfaces, packages, and polymorphism. It provides examples to illustrate single inheritance, multilevel inheritance, method overloading, constructor overloading, and access modifiers like public, private and protected. It contains 8 questions asking to write programs demonstrating these concepts through problems involving defining classes for employees, rectangles, boxes, persons etc and performing tasks like calculating areas, volumes, salaries etc.

Uploaded by

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

INHERITANCE,

INTERFACE AND Java Programming

PACKAGE
INHERITANCE, INTERFACE AND PACKAGE

1) Write a program to implement following inheritance


(Summer 15) 4 marks

class person
{
String name;
int age;
void accept(String n,int a)
{
name=n;
age=a;
}
void display()
{
System.out.println("name--->"+name);
System.out.println("age--->"+age);
}
}
class employee extends person
{
String emp_designation;
float emp_salary;
void accept_emp(String d,float s)
{
emp_designation=d;
emp_salary=s;
}
void emp_dis()
{
INHERITANCE, INTERFACE AND PACKAGE

System.out.println("emp_designation-->"+emp_designation);
System.out.println("emp_salary-->"+emp_salary);
}
}
class single_demo
{
public static void main(String ar[])
{
employee e=new employee();
e.accept("ramesh",35);
e.display();
e.accept_emp("lecturer",35000.78f);
e.emp_dis();
}
}

2) Create a class „Rectangle‟ that contains „length‟ and „width‟


as data members. From this class drive class box which has
additional data member „depth‟. Class „Rectangle‟ consists
of a constructor and an area ( ) function. The derived „Box‟
class have a constructor and override function named area ( )
which returns surface area of „Box‟ and a volume ( ) function.
Write a java program calling all the member function.
(Winter 16) 6 marks
import java.io.*;
class Rectangle
{
int length, width;
Rectangle(int length, int width)
{
this.length = length;
this.width = width;
}
int area()
{
return length*width;
}
}
INHERITANCE, INTERFACE AND PACKAGE

class Box extends Rectangle


{
int depth;
Box(int length, int width, int depth)
{
super(length, width);
this.depth = depth;
}
int area()
{
return 2*(length*width+width*depth+depth*length);
}
int volume(int l, int w, int d)
{
return l*w*d;
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter the length, width and depth");
int l = Integer.parseInt(bin.readLine());
int w = Integer.parseInt(bin.readLine());
int h = Integer.parseInt(bin.readLine());
Box b = new Box(l,w,h);
Rectangle r = new Rectangle(l,w);
System.out.println("Area of the Rectangle is :"+r.area());
System.out.println("Area of the Box is :"+b.area());
System.out.println("volume of the Rectangle is
:"+b.volume(l,w,h));
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
INHERITANCE, INTERFACE AND PACKAGE

3) Write a java program to implement multilevel inheritance with


4 levels of hierarchy. (Summer 18) 8 marks
class emp
{
int empid;
String ename;
emp(int id, String nm)
{
empid=id;
ename=nm;
}
}
class work_profile extends emp
{
String dept;
String job;
work_profile(int id, String nm, String dpt, String j1)
{
super(id,nm);
dept=dpt;
job=j1;
}
}
class salary_details extends work_profile
{
int basic_salary;
salary_details(int id, String nm, String dpt, String j1,int bs)
{
super(id,nm,dpt,j1);
basic_salary=bs;
}
double calc()
{
double gs;
gs=basic_salary+(basic_salary*0.4)+(basic_salary*0.1);
return(gs);
}
INHERITANCE, INTERFACE AND PACKAGE

}
class salary_calc extends salary_details
{
salary_calc(int id, String nm, String dpt, String j1,int bs)
{
super(id,nm,dpt,j1,bs);
}
public static void main(String args[])
{
salary_calc e1=new salary_calc(101,"abc","Sales","clerk",5000);
double gross_salary=e1.calc();
System.out.println("Empid :"+e1.empid);
System.out.println("Emp name :"+e1.ename);
System.out.println("Department :"+e1.dept);
System.out.println("Job :"+e1.job);
System.out.println("BAsic Salary :"+e1.basic_salary);
System.out.println("Gross salary :"+gross_salary);
}
}

4) What is single level inheritance? Explain with suitable


example. (Summer 17) 6 marks
Single level inheritance enables a derived class to inherit
properties and behaviour from a single parent class. It allows a
derived class to inherit the properties and behaviour of a base
class, thus enabling code reusability as well as adding new
features to the existing code. This makesthe code much more
elegant and less repetitive. Single level inheritance can be
represented by the following

Example:
class SingleLevelInheritanceParent {
int l;
INHERITANCE, INTERFACE AND PACKAGE

SingleLevelInheritanceParent(int l) {
this.l = l;
}
void area() {
int a = l*l;
System.out.println("Area of square :"+a);
}
}

class SingleLevelInheritanceChild extends


SingleLevelInheritanceParent
{
SingleLevelInheritanceChild(int l) {
super(l);
}
void volume() {
int v;
v= l*l*l;
System.out.println("Volume of the cube is "+v);
}
void area() {
int a;
a = 6*l*l;
System.out.println("Total surface area of a cube is "+a);
}
}

class SingleLevelInheritance {
public static void main(String args[]) {
SingleLevelInheritanceChild cube = new
SingleLevelInheritanceChild(2);
cube.volume();
cube.area();
}
}
INHERITANCE, INTERFACE AND PACKAGE

5) Explain inheritance and polymorphism features of Java.


(Winter 17) 6 marks
Inheritance: inheritance is the process by which one object
acquires the properties of another object. It supports the concept
of hierarchical classification. Without the use of hierarchies, each
object would need to define all the characteristics explicitly. By use
of inheritance, an object need only define those qualities that make
it unique within its class. It can inherit the general attributes from
its parent. It is the inheritance mechanism that makes it possible
for one object to be a specific instance of a more general case. For
e.g.: Parrot is a classification of Bird. Therefore Parrot is a
subclass of Bird. Parrot inherits a lot many features of the class
Bird plus some additional features
class Bird {
}
class Parrot extends Bird {
}

Polymorphism: it is a feature that allows one interface to be used


for a general class of actions. The specific action is determined by
the exact nature of the situation. By this concept it is possible to
design a generic interface to a group of related activities
For E.g:- void add(int a, int b){
int sum = a+b;
System.out.println(sum);
}
void add(float a, float b){
float sum = a+b;
System.out.println(sum);
}

6) Write a java program to implement visibility controls such as


public, private, protected access modes. Assume suitable
data, if any. (Summer 18) 6 marks
Public access specifier:
class Hello
{
public int a=20;
INHERITANCE, INTERFACE AND PACKAGE

public void show()


{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a);
obj.show();
}
}

private access specifier:


class Hello
{
private int a=20;
private void show()
{
System.out.println("Hello java");
}
}
public class Demo
{
public static void main(String args[])
{
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access
private data
obj.show(); //Compile Time Error, you can't access private
methods
}
}
INHERITANCE, INTERFACE AND PACKAGE

protected access specifier:


// save A.java
package pack1;
public class A
{
protected void show()
{
System.out.println("Hello Java");
}
}
//save B.java
package pack2;
import pack1.*;
class B extends A
{
public static void main(String args[]){
B obj = new B();
obj.show();
}
}

7) Explain method overloading with example.


(Winter 15) 4 marks
Method Overloading means to define different methods with the
same name but different parameters lists and different definitions.
It is used when objects are required to perform similar task but
using different input parameters that may vary either in number or
type of arguments. Overloaded methods may have different return
types. It is a way of achieving polymorphism in java.
int add( int a, int b) // prototype 1
int add( int a , int b , int c) // prototype 2
double add( double a, double b) // prototype 3
Example:
class Sample
{
int addition(int i, int j)
{
return i + j ;
INHERITANCE, INTERFACE AND PACKAGE

}
String addition(String s1, String s2)
{
return s1 + s2;
}
double addition(double d1, double d2)
{
return d1 + d2;
}
}
class AddOperation
{
public static void main(String args[])
{
Sample sObj = new Sample();
System.out.println(sObj.addition(1,2));
System.out.println(sObj.addition("Hello ","World"));
System.out.println(sObj.addition(1.5,2.2));
}
}

8) Define a class person with data member as Aadharno, name,


Panno implement concept of constructor overloading. Accept
data for 5 object and print it. (Winter 17) 8 marks
import java.io.*;
class Person {
intAadharno;
String name;
String Panno;
Person(intAadharno, String name, String Panno) {
this.Aadharno = Aadharno;
this.name = name;
this.Panno = Panno;
}
Person(intAadharno, String name) {
this.Aadharno = Aadharno;
this.name = name;
INHERITANCE, INTERFACE AND PACKAGE

Panno = "Not Applicable";


}
void display() {
System.out.println("Aadharno is :"+Aadharno);
System.out.println("Name is: "+name);
System.out.println("Panno is :"+Panno);
}
public static void main(String ar[]) {
BufferedReaderbr = new
BufferedReader(newInputStreamReader(System.in));
Person p, p1, p2, p3, p4;
int a;
String n, pno;
try {
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
System.out.println("Enter panno");
pno = br.readLine();
p = new Person(a,n,pno);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
System.out.println("Enter panno");
pno = br.readLine();
p1 = new Person(a,n,pno);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
p2 = new Person(a,n);
System.out.println("Enter Aadhar no");
a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
p3 = new Person(a,n);
INHERITANCE, INTERFACE AND PACKAGE

System.out.println("Enter Aadhar no");


a = Integer.parseInt(br.readLine());
System.out.println("Enter name");
n = br.readLine();
System.out.println("Enter panno");
pno = br.readLine();
p4 = new Person(a,n,pno);
p.display();
p1.display();
p2.display();
p3.display();
p4.display();
} catch(Exception e) {
System.out.println("Exception caught"+e);
}
}
}

9) Explain method overriding with suitable example.


(Winter 17) 4 marks
Method Overriding in Java:
If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in java. If subclass
provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method
overriding. Method overriding is used for runtime polymorphism.
Example:
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
INHERITANCE, INTERFACE AND PACKAGE

10) Write a single program to implement inheritance and


polymorphism in java. (Winter 17) 6 marks
class Employee {
String name;
String address;
int number;
Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " +
this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public intgetNumber() {
return number;
}
}
class Salary extends Employee {
private double salary;
Salary(String name, String address, int number, double salary) {
super(name, address, number);
INHERITANCE, INTERFACE AND PACKAGE

setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary>= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
public class Demo {
public static void main(String [] args) {
Salary s = new Salary("RAM", "Dadar", 3, 3600.00);
Employee e = new Salary("John ", "Thane", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--
");
e.mailCheck();
}
}

11) State the use of final keyword w. r. t. a method and the


variable with suitable example. (Summer 15) 4 marks
All variable and methods can be overridden by default in subclass.
In order to prevent this, the final modifier is used. Final modifier
can be used with variable, method or class.
INHERITANCE, INTERFACE AND PACKAGE

final variable: the value of a final variable cannot be changed.


final variable behaves like class variables and they do not take any
space on individual objects of the class.
Eg of declaring final variable: final int size = 100;

final method: making a method final ensures that the functionality


defined in this method will never be altered in any way, ie a final
method cannot be overridden.
Eg of declaring a final method:
final void findAverage()
{
//implementation
}

12) Describe final method and final variable with respect to


inheritance. (Summer 16) 6 marks
final method: making a method final ensures that the functionality
defined in this method will never be altered in any way, ie a final
method cannot be overridden.
E.g.of declaring a final method:
final void findAverage() {
//implementation
}
EXAMPLE
class A
{ final void show()
{
System.out.println(“in show of A”);
}
}
class B extends A
{
void show() // can not override because it is declared with final
{
System.out.println(“in show of B”);
}
}
INHERITANCE, INTERFACE AND PACKAGE

final variable: the value of a final variable cannot be changed.


final variable behaves like class variables and they do not take any
space on individual objects of the class.
E.g. of declaring final variable:
final int size = 100;

13) State three uses of final keyword. (Summer 17) 4 marks


Uses of final keyword:
Prevent overriding of method: To disallow a method to be
overridden final can be used as a modifier at the start of
declaration. Methods written as final cannot be overridden.
e.g.
class test
{
final void disp() //prevents overidding
{
System.out.println(“In superclass”);
}
}
class test1 extends test {
voiddisp(){ // ERROR! Can't override
System.out.println("Illegal!");
}
}

Prevent inheritance: Final can be used to even disallow the


inheritance, to do this a class can be defined with final modifier,
declaring a class as final declares all its method as final
e.g.
final class test
{
void disp()
{
System.out.println(“In superclass”);
}
}Class test1 extends test // error as class test is final
{

INHERITANCE, INTERFACE AND PACKAGE

Declaring final variable: Variable declared final, it is constant


which will not and cannot change.
final int FILE_NEW = 1;

14) Describe use of “super” and “this” with respect to


inheritance. (Summer 16, Winter 17) 4 marks and 6 marks
respectively
Using inheritance, you can create a general class that defines
traits common to a set of related items. This class can then be
inherited by other, more specific classes, each adding those things
that are unique to it. In the terminology of Java, a class that is
inherited is called a superclass. The class that does the inheriting
is called a subclass. Therefore, a subclass is a specialized version
of a superclass.
Whenever a subclass needs to refer to its immediate superclass, it
can do so by use of the keyword super.
Super has two general forms. The first calls the super class
constructor. The second is used to access a member of the
superclass that has been hidden by a member of a subclass.
super() is used to call base class constructer in derived class.
Super is used to call overridden method of base class or
overridden data or evoked the overridden data in derived class.
e.g use of super()
class BoxWeightextends Box
{
BowWeight(int a ,intb,int c ,int d)
{
super(a,b,c) // will call base class constructer Box(int a, int b, int c)
weight=d // will assign value to derived class member weight.
}
e.g. use of super.
Class Box
{
Box()
{
}
INHERITANCE, INTERFACE AND PACKAGE

void show()
{
//definition of show
}
} //end of Box class
Class BoxWeight extends Box
{
BoxWeight()
{
}
void show() // method is overridden in derived
{
Super.show() // will call base class method
}
}

The this Keyword


Sometimes a method will need to refer to the object that invoked it.
To allow this, Java defines the this keyword. this can be used
inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was
invoked. You can use this anywhere a reference to an object of the
current class‟ type is permitted. To better understand what this
refers to, consider the following version of Box( ): // A redundant
use of this. Box(double w, double h, double d) { this.width = w;
this.height = h; this.depth = d; }

Instance Variable Hiding


when a local variable has the same name as an instance variable,
the local variable hides the instance variable. This is why width,
height, and depth were not used as the names of the parameters
to the Box( ) constructor inside the Box class. If they had been,
then width would have referred to the formal parameter, hiding the
instance variable width.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
INHERITANCE, INTERFACE AND PACKAGE

this.height = height;
this.depth = depth;
}

15) State the use of ‘super’ and ‘final’ keyword w.r.t


inheritance with example. (Winter 15) 6 marks
when you will want to create a superclass that keeps the details of
its implementation to itself (that is, that keeps its data members
private). In this case, there would be no way for a subclass to
directly access or initialize these variables on its own. Whenever a
subclass needs to refer to its immediate super class, it can do so
by use of the keyword super. As constructer can not be inherited,
but derived class can called base class constructer using super()
super has two general forms.
The first calls the super class constructor. (super() method)
The second is used to access a member of the super class that
has been hidden by a member of a subclass.
Using super () to Call Super class Constructors
A subclass can call a constructor method defined by its super
class by use of the following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the
constructor in the super class. super( ) must always be the first
statement executed inside a subclass‟ constructor. A Second Use
for super
The second form of super acts somewhat like this, except that it
always refers to the super class of the subclass in which it is used.
This usage has the following general form: super.member
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in
the super class.
Example:
// Using super to overcome name hiding.
class A
{
int i;
}
INHERITANCE, INTERFACE AND PACKAGE

// Create a subclass by extending class A.


class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void 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 subOb = new B(1, 2);
subOb.show();
}
}

Final keywords
The keyword final has three uses. First, it can be used to create
the equivalent of a named constant.( in interface or class we use
final as shared constant or constant.) other two uses of final apply
to inheritance

Using final to Prevent Overriding


While method overriding is one of Java‟s most powerful features,
there will be times When you will want to prevent it from occurring.
To disallow a method from being overridden, specify final as a
modifier at the start of its declaration. Methods declared as final
cannot be overridden. The following fragment illustrates final:
class A
{
INHERITANCE, INTERFACE AND PACKAGE

final void meth()


{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
As base class declared method as a final, derived class cannot
override the definition of base class methods.

16) Which are the restrictions present for static declared


methods? (Summer 18) 4 marks
Restrictions on static variables:
a) Static variables become class variables.
b) They get initialized only once in the entire life time of the
program.
c) They cannot be called by the object of the class in which
they are defied.
d) A static method can operate only on static variables without
objects otherwise non static variables cannot be handled by
a static method without using their respective class object.

17) Write syntax of defining interface .Write any major two


differences between interface and a class.
(Summer 16) 6 marks
Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
return_type method_name2(parameter list);
type final-variable 1 = value1;
type final-variable 2 = value2;
INHERITANCE, INTERFACE AND PACKAGE

18) What is meant by interface? State its need and write


syntax and features of interface. (Summer 17) 8 marks
Interface is the mechanism by which multiple inheritance is
possible in java. It is a reference type in Java. An interface has all
the methods undefined. For a java class to inherit the properties of
an interface, the interface should be implemented by the child
class using the keyword “implements”. All the methods of the
interface should be defined in the child class.
Example:
interface MyInterface{
int strength=60;
void method1();
void method2();
}
public class MyClass implements MyInterface {
int total;
INHERITANCE, INTERFACE AND PACKAGE

MyClass(int t) {
total = t;
}
public void method1() {
int avg = total/strength;
System.out.println("Avg is "+avg);
}
public void method2() {
}
public static void main(String a[]) {
MyClass c = new MyClass(3600);
c.method1();
}
}

Need:
A java class can only have one super class. Therefore for
achieving multiple inheritance, that is in order for a java class to
get the properties of two parents, interface is used. Interface
defines a set of common behaviours. The classes implement the
interface, agree to these behaviours and provide their own
implementation to the behaviours.

Syntax:
interface InterfaceName {
int var1 = value;
int var2 = value;
public return_type methodname1(parameter_list) ;
public return_type methodname2(parameter_list) ;
}

Features:
Interface is defined using the keyword “interface”. Interface is
implicitly abstract. All the variables in the interface are by default
final and static. All the methods of the interface are implicitly public
and are undefined (or implicitly abstract). It is compulsory for the
subclass to define all the methods of an interface. If all the
INHERITANCE, INTERFACE AND PACKAGE

methods are not defined then the subclass should be declared as


an abstract class.
19) What is meant by an interface? State its need and write
syntax and features of an interface. Give one example
(Winter 15) 8 marks
Defining an Interface:
Interface is also known as kind of a class. So, interface also
contains methods and variables but with major difference the
interface consists of only abstract method (i.e., methods are not
defined, these are declared only) and final fields (shared
constants). This means that interface do not specify any code to
implement those methods and data fields contains only constants.
Therefore, it is the responsibility of the class that implements an
interface to define the code for implementation of these methods.
An interface is defined much like class.

Syntax:
access interface InterfaceName
{
return_type method_name1(parameter list);
….
return_type method_nameN(parameter list);
type final-variable 1 = value1;
….
type final-variable N = value2;
}

Features:
Variable of an interface are explicitly declared final and static (as
constant) meaning that the implementing the class cannot change
them they must be initialize with a constant value all the variable
are implicitly public of the interface, itself, is declared as a public
Method declaration contains only a list of methods without
anybody statement and ends with a semicolon the method are,
essentially, abstract methods there can be default implementation
of any method specified within an interface each class that include
an interface must implement all of the method
INHERITANCE, INTERFACE AND PACKAGE

Need:
To achieve multiple Inheritance.
We can implement more than one Interface in the one class.
Methods can be implemented by one or more class.

Example:
interface sports
{
int sport_wt=5;
public void disp();
}
class Test
{
int roll_no;
String name;
int m1,m2;
Test(int r, String nm, int m11,int m12)
{
roll_no=r;
name=nm;
m1=m11;
m2=m12;
}
}
class Result extends Test implements sports
{
Result (int r, String nm, int m11,int m12)
{
super (r,nm,m11,m12);
}
public void disp()
{
System.out.println("Roll no : "+roll_no);
System.out.println("Name : "+name);
System.out.println("sub1 : "+m1);
System.out.println("sub2 : "+m2);
System.out.println("sport_wt : "+sport_wt);
int t=m1+m2+sport_wt;
INHERITANCE, INTERFACE AND PACKAGE

System.out.println("total : "+t);
}
public static void main(String args[])
{
Result r= new Result(101,"abc",75,75);
r.disp();
}
}

20) Write a java program (Winter 16) 6 marks

import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2;
Student(String name, int roll_no, double m1, double m2)
{
this.name = name;
this.roll_no = roll_no;
this.m1 = m1;
this.m2 = m2;
}
}
interface exam {
public void per_cal();
}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)
{
INHERITANCE, INTERFACE AND PACKAGE

super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of
the student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());
double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
} catch(Exception e)
{
System.out.println("Exception caught"+e);
}
}
}
INHERITANCE, INTERFACE AND PACKAGE

21) Write a program to implement following inheritance:


(Summer 17) 4 marks

interface gross
{
int ta=1000;
int da=4000;
public void gross_sal();
}
class employee
{
String name="Abc";
int basic_sal=8000;
}
class salary extends employee implements gross
{
int hra;
int total=0;
salary(int h)
{
hra=h;
}
public void gross_sal()
{
total=basic_sal+ta+da+hra;
}
void disp_sal()
{
INHERITANCE, INTERFACE AND PACKAGE

gross_sal();
System.out.println("Name :"+name);
System.out.println("Total salary :"+total);
}
public static void main(String args[])
{
salary s = new salary(3000);
s.disp_sal();
}
}

22) Explain with example how interface is used to achieve


multiple Inheritance in Java.
(Summer 15, 16, 18) 6 marks, 8 marks and 4 marks
respectively
Multiple inheritances is not possible in java. Multiple inheritance
happens when a class is derived from two or more parent classes.
Java classes cannot extend more than one parent classes, instead
it uses the concept of interface to implement the multiple
inheritance. It contains final variables and the methods in an
interface are abstract. A sub class implements the interface. When
such implementation happens, the class which implements the
interface must define all the methods of the interface. A class can
implement any number of interfaces.
Example of multiple inheritance:
import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2;
Student(String name, int roll_no, double m1, double m2)
{
this.name = name;
this.roll_no = roll_no;
this.m1 = m1;
this.m2 = m2;
}
INHERITANCE, INTERFACE AND PACKAGE

}
interface exam {
public void per_cal();
}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)
{
super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of the
student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());
double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
} catch(Exception e)
{
INHERITANCE, INTERFACE AND PACKAGE

System.out.println("Exception caught"+e);
}
}
}

23) How multiple inheritance is achieved in java? Explain


with proper program. (Winter 16) 8 marks
Inheritance is a mechanism in which one object acquires all the
properties and behaviours of parent object. The idea behind
inheritance in java is that new classes can be created that are built
upon existing classes.
Multiple inheritance happens when a class is derived from two or
more parent classes. Java classes cannot extend more than one
parent classes, instead it uses the concept of interface to
implement the multiple inheritance.
It contains final variables and the methods in an interface are
abstract. A sub class implements the interface. When such
implementation happens, the class which implements the interface
must define all the methods of the interface. A class can
implement any number of interfaces.
Eg:
import java.io.*;
class Student
{
String name;
int roll_no;
double m1, m2;
Student(String name, introll_no, double m1, double m2)
{
this.name = name;
this.roll_no = roll_no;
this.m1 = m1;
this.m2 = m2;
}
}
interface exam
{
public void per_cal();
INHERITANCE, INTERFACE AND PACKAGE

}
class result extends Student implements exam
{
double per;
result(String n, int r, double m1, double m2)
{
super(n,r,m1,m2);
}
public void per_cal()
{
per = ((m1+m2)/200)*100;
System.out.println("Percentage is "+per);
}
void display()
{
System.out.println("The name of the student is"+name);
System.out.println("The roll no of the student is"+roll_no);
per_cal();
}
public static void main(String args[])
{
BufferedReader bin = new BufferedReader(new
InputStreamReader(System.in));
try
{
System.out.println("Enter name, roll no mark1 and mark 2 of the
student");
String n = bin.readLine();
int rn = Integer.parseInt(bin.readLine());
double m1 = Double.parseDouble(bin.readLine());
double m2 = Double.parseDouble(bin.readLine());
result r = new result(n,rn,m1,m2);
r.display();
}
catch(Exception e)
{
System.out.println("Exception caught"+e);
}
INHERITANCE, INTERFACE AND PACKAGE

}
}

24) What is the multiple inheritance? Write a java program to


implement multiple inheritance. (Winter 17) 6 marks
Multiple inheritance: is a feature in which a class inherits
characteristics and features from more than one super class or
parent class.

Java cannot have more than one super class. Therefore, interface
is used to support multiple inheritance in java. Interface specifies
what a class must do but not how it is done.

Eg: interface MyInterface{


int strength=60;
void method1();
}
class MyBaseClass {
String str;
MyBaseClass(String str) {
this.str = str;
}
public void display() {
System.out.println("Class: "+str);
}
}
public class MyClass extends MyBaseClass implements
MyInterface
{
float total;
MyClass(String str, float t) {
super(str);
total = t;
}
INHERITANCE, INTERFACE AND PACKAGE

public void method1() {


float avg = total/strength;
System.out.println("Avg is "+avg);
}
public static void main(String a[]) {
MyClass c = new MyClass("Fifth Sem",1300.0f);
c.display();
c.method1();
}
}

25) Write a java program to extend interface assuming


suitable data. (Summer 18) 6 marks
interface A
{
int x=20;
void display();
}
interface B extends A
{
int y=30;
void show();
}
class C implements B
{
public void display()
{
System.out.println("A's X="+x);
}
public void show()
{
System.out.println("A's X="+x);
System.out.println("B's Y="+y);
}
public static void main(String args[])
{
C obj=new C();
obj.display();
INHERITANCE, INTERFACE AND PACKAGE

obj.show();
}
}

26) State any four system packages along with their use.
(Winter 15) 4 marks
a) 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, strings,
math functions, threads and exceptions
b) java.util – language utility classes such as vectors, hash
tables, random numbers, date etc.
c) java.io – input/output support classes. They provide facilities
for the input and output of data
d) java.awt – set of classes for implementing graphical user
interface. They include classes for windows, buttons, lists,
menus and so on
e) java.net – classes for networking. They include classes for
communicating with local computers as well as with internet
servers.
f) java.applet – classes for creating and implementing applets.

27) List any four built-in packages from Java API along with
their use. (Summer 17) 4 marks
a) java.lang: Contains Language support classes which are
used by Java compiler during compilation of program
b) java.util: Contains language utility classes such as vectors,
hash tables, random numbers, date etc.
c) java.io: Contains I/O support classes which provide facility
for input and output of data.
d) java.awt: Contains a set of classes for implementing
graphical user interface.
e) java.aplet: Contains classes for creating and implementing
applets.
f) java.sql: Contains classes for database connectivity.
g) java.net: Contains classes for networking.
INHERITANCE, INTERFACE AND PACKAGE

28) Enlist any four built in packages in java API with atleast
two class name from each package (Winter 17) 4 marks
a) 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, strings,
math functions, threads and exceptions
classes: Thread, String
b) java.util – language utility classes such as vectors, hash
tables, random numbers, date etc
classes: Date,Collection,Vector
c) java.io – input/output support classes. They provide facilities
for the input and output of data
classes: FileReader, FileWriter
d) java.awt – set of classes for implementing graphical user
interface. They include classes for windows, buttons, lists,
menus and so on
classes: Button,Label
e) java.net – classes for networking. They include classes for
communicating with local computers as well as with internet
servers
classes: Socket,URL

29) What is package? How to create package? Explain with


suitable example. (Winter 15) 6 marks
Java provides a mechanism for partitioning the class namespace
into more manageable parts called package (i.e package are
container for a classes). The package is both naming and visibility
controlled mechanism. Package can be created by including
package as the first statement in java source code. Any classes
declared within that file will belong to the specified package.
The syntax for creating package is:
package pkg;
Here, pkg is the name of the package
eg : package mypack;
Packages are mirrored by directories. Java uses file system
directories to store packages. The class files of any classes which
are declared in a package must be stored in a directory which has
same name as package name. The directory must match with the
INHERITANCE, INTERFACE AND PACKAGE

package name exactly. A hierarchy can be created by separating


package name and sub package name by a period(.) as
pkg1.pkg2.pkg3; which requires a directory structure as
pkg1\pkg2\pkg3.
The classes and methods of a package must be public.

Syntax:
To access package 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|*);

Example:
package1:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h)); }
}
}

Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
INHERITANCE, INTERFACE AND PACKAGE

30) What is package? How do we create it? Give the


example to create and to access package.
(Winter 17) 8 marks
Package is a name space that organizes a set of related classes
and interfaces. It also provides access protection and removes
name collision.
Packages can be categorized into two: - built-in and user defined.

Creation of user defined package:


To create a package a physical folder by the name of the package
should be created in the computer.

Example: we have to create a package myPack, so we create a


folder
d:\myPack
The java program is to be written and saved in the folder myPack.
The first line in the java program should be package ;
followed by imports and the program logic.
package myPack;
importjava.util.*;
public class Myclass {
public void myMethod() {
System.out.println("Inside package");
}
}

Access user defined package:


To access a user defined package, we need to import the package
in our program. Once we have done the import we can create the
object of the class from the package and thus through the object
we can access the instance methods.

import myPack.*;
public class MyClassExample{
public static void main(String a[]) {
Myclass c= new Myclass();
INHERITANCE, INTERFACE AND PACKAGE

c.myMethod();
}
}

31) Write the effect of access specifiers public, private and


protected in package (Summer 15) 4 marks
Visibility restriction must be considered while using packages and
inheritance in program visibility restrictions are imposed by various
access protection modifiers. packages acts as container for
classes and other package and classes acts as container for data
and methods.
Data members and methods can be declared with the access
protection modifiers such as private, protected and public.
Following table shows the access protections

32) What is package? State how to create and access user


defined package in Java. (Summer 17) 6 marks
Package is a name space that organizes a set of related classes
and interfaces. Conceptually, it is similar to the different folders in
a computer. It also provides access protection and removes name
collision.
Packages can be categorized into two:- built-in and user
defined.
INHERITANCE, INTERFACE AND PACKAGE

Creation of user defined package:


To create a package a physical folder by the name should be
created in the computer.
Example: we have to create a package myPack, so we create a
folder d:\myPack
The java program is to be written and saved in the folder myPack.
To add a program to the package, the first line in the java program
should be package; followed by imports and the program logic.
package myPack;
import java.util;
public class Myclass {
//code
}

Access user defined package:


To access a user defined package, we need to import the package
in our program. Once we have done the import we can create the
object of the class from the package and thus through the object
we can access the instance methods.
import mypack.*;
public class MyClassExample{
public static void main(String a[]) {
Myclass c= new Myclass();
}
}

33) Which are the ways to access package from another


package? Explain with example. (Summer 18) 4 marks
There are two ways to access the package from another package.
a) import package.*;
b) import package.classname;

using packagename.*
If you use package.* then all the classes and interfaces of
this package will be accessible but not subpackages. The
import keyword is used to make the classes and interfaces of
another package
INHERITANCE, INTERFACE AND PACKAGE

accessible to the current package.


E.g.
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}}

import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Using packagename.classname
If you import packagename.classname then only declared
class of this package will be accessible.
Eg.
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}

34) Design a package containing a class which defines a


method to find area of rectangle. Import it in java application
to calculate area of a rectangle. (Summer 16) 4 marks
package Area;
public class Rectangle
{
doublelength,bredth;
public doublerect(float l,float b)
INHERITANCE, INTERFACE AND PACKAGE

{
length=l;
bredth=b;
return(length*bredth);
}
}
import Area.Rectangle;
class RectArea
{
public static void main(String args[])
{
Rectangle r=new Rectangle( );
double area=r.rect(10,5);
System.out.println(“Area of rectangle= “+area);
}
}

35) What is package? State any four system packages along


with their use? How to add class to a user defined packages?
(Summer 15) 8 marks
Package: Java provides a mechanism for partitioning the class
namespace into more manageable parts. This mechanism is the
“package”. The package is both naming and visibility controlled
mechanism.

System packages with their use:


a) 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, strings,
math functions, threads and exceptions.
b) Java.util – language utility classes such as vectors, hash
tables, random numbers, date etc.
c) java.io – input/output support classes. They provide facilities
for the input and output of data
d) java.awt – set of classes for implementing graphical user
interface. They include classes for windows, buttons, lists,
menus and so on.
INHERITANCE, INTERFACE AND PACKAGE

e) java.net – classes for networking. They include classes for


communicating with local computers as well as with internet
servers.
f) java.applet – classes for creating and implementing applets.

To add a class to user defined package


a) Include a package command as the first statement in a Java
source file.
b) Any classes declared within that file will belong to the
specified package
c) The package statement defines a name space in which
classes are stored.
d) Example:
package MyPack;
public class Balance
{
.
.
.
}
Then class Balance in included inside a user defined
package “MyPack”.

36) How to add new class to a package? Explain with an


example. (Summer 18) 4 marks
Create a package: simply include a package command as the first
statement in a Java source file.
Include classes: Any classes declared within that file will belong to
the 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 pkg; //Here, pkg is the name of the package
public class class_name
{
//class body goes here
}
INHERITANCE, INTERFACE AND PACKAGE

Example:
package package1;
public class Box
{
int l= 5;
int b = 7;
int h = 8;
public void display()
{
System.out.println("Volume is:"+(l*b*h)); }
}
}

Source file:
import package1.Box;
class VolumeDemo
{
public static void main(String args[])
{
Box b=new Box();
b.display();
}
}

37) What is interface? How to add interfaces to packages.


(Winter 16) 4 marks
Interface:
a) It is similar to class but mainly used to define abstraction in
Java
b) It contains all abstract methods and final variables inside it.
c) Interfaces have to be implemented by a class.
d) It is mainly used to achieve multiple inheritance in Java.

To add interface to packages:


a) Begin the program with ‘package < package name>;
b) Declare public interface
c) Declare final variables and abstract methods required.
INHERITANCE, INTERFACE AND PACKAGE

d) Save and compile the file.


e) Create a folder with exactly same name as package name.
f) Copy class of package inside this folder.
g) Create java source code which requires interface from
package
h) Import the created package inside it and use.

You might also like