Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Document From Kathawde Komal

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

unit 3:Inheritance,interface&package

1] Explain abstract class with suitable example.

A class that is declared with abstract keyword is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).Abstraction is a process of hiding the
implementation details and showing only functionality to the user. Another way, it shows only
important things to the user and hides the internal details.A method must be always redefined
in a subclass of an abstract class, as abstract class does not contain method body. Thus abstract
makes overriding compulsory.Class containing abstract method must be declared as
abstract.You can not declare abstract constructor, and so, objects of abstract class cannot be
instantiated.

Syntax :

abstract class < classname>

abstract method1(…);

method2(….);

Example :

abstract class A

abstract void disp();

void show()

System.out.println(“show method is not abstract”);

}}

class B extends A

{
void disp()

System.out.println(“inside class B”);

}}

class test

public static void main(String args[])

B b = new B();

b.disp();

b.show();

}}

2] What is interface? How it is different from class? With suitable program explain the use of
interface.

Interface:

Exampl
e:

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;

System.out.println("total : "+t);

public static void main(String args[])

result r= new result(101,"abc",75,75);

r.disp();

}}

Output :

D:\>java result

Roll no : 101

Name : abc

sub1 : 75

sub2 : 75

sport_wt : 5

total : 155

3] What is final variable and methods? How it is different from abstract method?
4]

void gross_sal();

class Employee

String name;

float basic_sal;
Employee(String n, float b)

name=n;

basic_sal=b;

void display()

System.out.println("Name of Employee="+name);

System.out.println("Basic Salary of Employee="+basic_sal);

class salary extends Employee implements Gross

float hra;

salary(String n, float b, float h)

super(n,b);

hra=h;

void disp()

display();

System.out.println("HRA of Employee="+hra);

public void gross_sal()

double gross_sal=basic_sal+ta+hra;
System.out.println("TA of Employee="+ta);

System.out.println("DA of Employee="+da);

System.out.println("Gross Salary of Employee="+gross_sal);

class Empdetail

public static void main(String args[])

salary s=new salary("ABC",6000,4000);

s.disp();

s.gross_sal();

}}

5] What is package? How do we create it?

Package: Packages are used for grouping a variety of classes & interfaces together. This

grouping is done according to functionality. Packages acts as containers of classes. Packages are
stored in hierarchical manner & are explicitly imported into new class definitions. Following
benefits are achieved by organizing classes into packages:

1. The classes contained in the packages of other programs can be easily reused.

2. In packages, classes can be unique compared with classes in other packages. That is two
classes in two different packages can have same name. They may be referred by their fully
qualified name, comprising package name & class name.3. Packages provide way to hide classes
thus preventing other programs or packages from accessing classes that are meant for internal
use only.4. Packages also provide a way for separating “design” from “coding”. First we can
design classes & decide their relationship & then we can implement Java code needed for
methods. It is possible to change implementation of any method without affecting rest of the
design.Java packages are therefore classified into two types. First category is known as Java API
packages & second is known as User defined packages.Creating Packages: First declare name of
package using package keyword followed by package name. This must be first statement in a
java source file. Here is an example:

package firstPackage; //package declaration


public class FirstClass //class definition

…..

….. (body of class)

…..

Here the package name is firstPackage. The class FirstClass is now considered a part of this
package. This listing would be saved as file called FirstClass.java & located in a director named
firstPackage. When source file is complied, Java will create a .class file & store it in same
directoryclass must be located in a directory that has same name as the package, & this
directory should be a subdirectory of the directory where classes that will import package are
located. Creating package involves following steps:

1. Declare the package at beginning of a file using the form package packagename;

2. Define the class that is to be put in the package & declare it public

3. Create a subdirectory under directory where main source files are stored

4. Store listing as the classname.java file in the subdirectory created.

5. Compile the file. This creates .class file in the subdirectory

Case is significant & therefore subdirectory name must match package name exactly. Java
supports the concept of package hierarchy. This is done by specifying multiple names in a
package statement, separated by dots. Example: package firstPackage.secondPackage;This
approach allows us to group related classes into a package & then group related packages into
larger package. To store this package in subdirectory named firstPackage/secondPackage.A java
package file can have more than one class definition. in such cases only one of the classes may
be declared public & that class name with .java extension is the source file name. When a
source file with more than one class definition is complied, java creates independent .class files
for these classes.

6] Write the effect of access specifiers public, private and protected in package.

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
7] Explain with example how to achieve multiple inheritance with interface.

Multiple inheritances: It is a type of inheritance where a derived class may have more than one
parent class. It is not possible in case of java as you cannot have two classes at the parent level
Instead there can be one class and one interface at parent level to achieve multiple
interface.Interface is similar to classes but can contain on final variables and abstract method.
Interfaces can be implemented to a derived class.
{

result r= new result(101,"abc",75,75);

r.disp();

}}

8] What is package? State any four system packages along with their use? How to add class to a
user defined packages?

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:
1. java.lang - language support classes. These are classes that java compiler itself uses and
therefore they are automatically imported. They include classes for primitive types,strings, math
functions, threads and exceptions.

2. java.util – language utility classes such as vectors, hash tables, random numbers, date etc.

3. java.io – input/output support classes. They provide facilities for the input and output of data

4. java.awt – set of classes for implementing graphical user interface. They

include classes for windows, buttons, lists, menus and so on.

5. java.net – classes for networking. They include classes for communicating

with local computers as well as with internet servers.

6. java.applet – classes for creating and implementing applets. To add a class to user defined
package :

1) Include a package command as the first statement in a Java source file.

2) Any classes declared within that file will belong to the specified package.

3) The package statement defines a name space in which classes are stored.

4) Example :

package MyPack;

public class Balance

Then class Balance in included inside a user defined package „MyPack‟

9] State the use of final keyword w. r. t. a method and the variable with suitable example

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.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

10] Write a program to implement following inheritance:

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()

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

}}

11]What is package? How to create package? Explain with suitable example.

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

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

12] State the use of ‘super’ and ‘final’ keyword w.r.t inheritance with example.

hen 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 superThe 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.memberHere, 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;

// 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

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 can not override the definition of base
class methods.

13]What is meant by an interface? State its need and write syntax and features of an

interface. Give one example.

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 consist 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:

1. 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

2. 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

Need:

1. To achieve multiple Inheritance.

2. We can implement more than one Interface in the one class.


3. 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;

System.out.println("total : "+t);

public static void main(String args[])

Result r= new Result(101,"abc",75,75);

r.disp();

}}

14]Explain method overloading with example.

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 ;

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

}}

15] State any four system packages along with their use.
1. java.lang - language support classes. These are classes that java compiler itself uses

and therefore they are automatically imported. They include classes for primitive

types, strings, math functions, threads and exceptions.

2. java.util – language utility classes such as vectors, hash tables, random numbers, date

etc.

3. java.io – input/output support classes. They provide facilities for the input and

output of data

4. java.awt – set of classes for implementing graphical user interface. They include

classes for windows, buttons, lists, menus and so on.

5. java.net – classes for networking. They include classes for communicating with

local computers as well as with internet servers.

6. java.applet – classes for creating and implementing applets.

16]Write syntax of defining interface .Write any major two differences between interface and a
class.
17]Describe with example how to achieve multiple inheritance with suitable program.

void display()

System.out.println("Name of Employee :"+name);

System.out.println("Basic Salary of Employee :"+basic_sal);

}
}

class Salary extends Employee implements Gross

{ double HRA;

Salary(String n, double b, double h)

super(n,b);

HRA=h;

void disp_sal()

{ display();

System.out.println("HRA of Employee :"+hra);

public void gross_sal()

double gross_sal=basic_sal + TA + DA + HRA;

System.out.println("Gross salary of Employee :"+gross_sal);

class EmpDetails

{ public static void main(String args[])

{ Salary s=new Salary("Sachin",8000,3000);

s.disp_sal();

s.gross_sal();

18]Describe use of „super‟ and „this‟ with respect to inheritance.


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.

Superhas 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()
{

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;

this.height = height;

this.depth = depth;

19]Describe final method and final variable with respect to inheritance.

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

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;

20]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

package Area;

public class Rectangle

doublelength,bredth;

public doublerect(float l,float b)

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

21]Write a java program

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)

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

}}}

22]How multiple inheritance is achieved in java? Explain with

proper program.

Inheritance is a mechanism in which one object acquires all the

properties and behaviors 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();

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

23]What is interface? How to add interfaces to packages.

Interface:

1) It is similar to class but mainly used to define abstraction in Java

2) It contains all abstract methods and final variables inside it.

3) Interfaces have to be implemented by a class.

4) It is mainly used to achieve multiple inheritance in Java.

To add interface to packages:

1) Begin the program with ‘package < package name>;

2) Declare public interface


3) Declare final variables and abstract methods required.

4) Save and compile the file.

5) Create a folder with exactly same name as package name

6) Copy class of package inside this folder.

7) Create java source code which requires interface from package

8) Import the created package inside it and use.

OR

A) Creation of package containing interface

package mypack;

public interface test

public int x=5;

public abstract void display();

B) Importing package inside another java code

import mypack.test;

class test1 implements test

public void display()

System.out.println("x from interface :"+x);

public static void main(String args[])

test1 t1 = new test1();


t1.display();

24]What is single level inheritance? Explain with suitable example.

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


public static void main(String ar[]) {

SingleLevelInheritanceChild cube = new

SingleLevelInheritanceChild(2);

cube.volume();

cube.area();

25]What is package? State how to create and access user defined


package in Java.

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.

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 <name>; 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();

26]What is meant by interface? State its need and write syntax and

features of interface

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;

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

methods are not defined then the subclass should be declared as an

abstract class.

27]State three uses of final keyword.

Uses of final keyword:

1. 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!");

2. 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

3. Declaring final variable:

Variable declared final, it is constant which will not and can not

change.

final int FILE_NEW = 1;

28]Write a program to implement following inheritance:


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()

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

29]Explain inheritance and polymorphism features of Java.

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

30]What is the multiple inheritance? Write a java program to

implement multiple inheritance.


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;

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

31]Define a class person with data member as Aadharno, name,

Panno implement concept of constructor overloading. Accept

data for 5 object and print it.

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

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

}
}

32]What is package? How do we create it? Give the example to

create and to access package.

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 <name>;

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

c.myMethod();

33]Explain method overriding with suitable example.

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

34]Enlist any four built in packages in java API with atleast two

class name from each package.

Inbuilt packages in java:

1. java.lang - language support classes. These are classes that java

compiler itself uses and therefore they are automatically

imported. They include classes for primitive types, strings, math

functions, threads and exceptions

classes : Thread, String ,

2. java.util – language utility classes such as vectors, hash tables,

random numbers, date etc

classes :Date,Collection,Vector

3. java.io – input/output support classes. They provide facilities for

the input and output of data

classes :FileReader, FileWriter

4. java.awt – set of classes for implementing graphical user

interface. They include classes for windows, buttons, lists,


menus and so on

classes :Button,Label

5. java.net – classes for networking. They include classes for

communicating with local computers as well as with internet

servers

classes :Socket,URL

35]What is importance of super and this keyword in inheritance?

Illustrate with suitable example.

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.

Superhas 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()

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;

this.height = height;

this.depth = depth;
}

36]What is interface? Describe its syntax and features.

Ans: Definition: Java does not support multiple inheritances with only classes.

Java provides an alternate approach known as interface to support concept of

multiple inheritance. An interface is similar to class which can define only

abstract methods and final variables.

Syntax:

access interface InterfaceName

Variables declaration;

Methods declaration;

Features:

 The interfaces are used in java to implementing the concept of

multiple inheritance.

 The members of an interface are always declared as constant i.e. their

values are final.

 The methods in an interface are abstract in nature. I.e. there is no code

associated with them.

 It is defined by the class that implements the interface.

 Interface contains no executable code.

 We are not allocating the memory for the interfaces.

 We can‘t create object of interface.

 Interface cannot be used to declare objects. It can only be inherited by


a class.

 Interface can only use the public access specifier.

 An interface does not contain any constructor.

 Interfaces are always implemented.

 Interfaces can extend one or more other interfaces.

37]What is package in Java? Write a program to create a package andimport the package in
another class.

Ans: Package: 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.

Syntax:

package pkg;

Here, pkg is the name of the package

Program:

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

38]What is use of super and final with respect to inheritance.

Ans: Super Keyword: The super keyword in Java is a reference variable which is

used to refer immediate parent class object. Whenever you create the instance

of subclass, an instance of parent class is created implicitly which is referred

by super reference variable.

Usage of Java super Keyword

 super can be used to refer immediate parent class instance variable.


 super can be used to invoke immediate parent class method.

 super() can be used to invoke immediate parent class constructor.

Example:

class A

int i;

A(int a, iont b)

i=a+b;

void add()

System.out.println(“sum of a and b=”+i);

class B extends A

int j;

B(int a,int b, int c)

super(a,b);

j=a+b+c;

void add()

{
super.add();

System.out.println(“Sum of a, b and c is:” +j);

Final Keyword: A parameter to a function can be declared with the keyword

“final”.

This indicates that the parameter cannot be modified in the function.

The final keyword can allow you to make a variable constant.

Example:

Final Variable: The final variable can be assigned only once. The value of a

final variable can never be changed.

final float PI=3.14;

Final Methods: A final method cannot be overridden. Which means even

though a sub class can call the final method of parent class without any issues

but it cannot override it.

Example:

class XYZ

final void demo(){

System.out.println("XYZ Class Method");

class ABC extends XYZ{

void demo()

{
System.out.println("ABC Class Method");

public static void main(String args[])

ABC obj= new ABC();

obj.demo();

The above program would throw a compilation error, however we can use the

parent class final method in sub class without any issues.

class XYZ

final void demo(){

System.out.println("XYZ Class Method");

class ABC extends XYZ

public static void main(String args[])

ABC obj= new ABC();

obj.demo();

Output:
XYZ Class Method

final class: We cannot extend a final class. Consider the below example:

final class XYZ

class ABC extends XYZ

void demo()

System.out.println("My Method");

public static void main(String args[])

ABC obj= new ABC();

obj.demo();

Output:

The type ABC cannot subclass the final class XYZ

39]Demonstrate the concept of method overriding with example.

Ans: Method overriding: In a class hierarchy, when method in a subclass has

same name, type, & parameter list as a method in superclass then the method

is said to override the method in superclass. When an overridden method is

called from within a subclass it will always refer to the version of method
defined by subclass. The version of method from superclass will be hidden.

Example:

class overridetest

int x,y;

overridetest(int a,int b)

x=a;

y=b;

void display()

System.out.println("x="+x);

System.out.println("y="+y);

class test extends overridetest

int z;

test(int a,int b,int c)

super(a,b);

z=c;

void display() //method overridden


{

super.display(); //call to super class display()

System.out.println("z="+z);

public static void main(String args[])

test t= new test(4,5,6);

t.display();

40]Write a program to demonstrate multiple inheritances.

Ans: interface sports

int sports_weightage=5;

void calc_total();

class person

String name;

String category;

person(String nm,String c)

name=nm;

category=c;
}

class student extends person implements sports

int marks1,marks2;

student(String n,String c, int m1,int m2)

super(n,c);

marks1=m1;

marks2=m2;

public void calc_total()

int total;

if (category.equals("sportsman"))

total=marks1+marks2+sports_weightage;

else

total=marks1+marks2;

System.out.println("Name="+name);

System.out.println("Category ="+category);

System.out.println("Marks1="+marks1);

System.out.println("Marks2="+marks2);

System.out.println("Total="+total);

public static void main(String args[])


{

student s1=new student("ABC","sportsman",67,78);

student s2= new student("PQR","non-sportsman",67,78);

s1.calc_total();

s2.calc_total();

41]Write syntax to inherit one interface into another interface.

An Interface can extend another interface similarly to the way that a class can

extend another class. The extends keyboard is used to extends an interface and

the child interface inherits the method of the parent interface.

Syntax:

Interface class2 extends class1

Body of class2

Example:

Interace A

Int code=11;

String name=”Computer”;

Interface B extends A
{

Void display();

42]Explain package creation with suitable example.

Ans 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.

Syntax:

package pkg;

Here, pkg is the name of the package

eg : package mypack;

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 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.

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

43]Explain dynamic method dispatch.


Dynamic Method Dispatch

1. Dynamic method dispatch is a technique by which call to a overridden

method is resolved at runtime, rather than compile time.

2. When an overridden method is called by a reference, then which version

of overridden method is to be called is decided at runtime according to

the type of object it refers.

3. Dynamic method dispatch is performed by JVM not compiler.

Dynamic method dispatch allows java to support overriding of methods

and perform runtime polymorphism.

4. It allows subclasses to have common methods and can redefine specific

implementation for them. This lets the superclass reference respond

differently to same method call depending on which object it is pointing.

Example:

class A {

void callme() {

System.out.println("Inside A's callme method");

class B extends A {

// override callme()

void callme() {

System.out.println("Inside B's callme method");

class C extends A {
// override callme()

void callme() {

System.out.println("Inside C's callme method");

class Dispatch {

public static void main(String args[]) {

A a = new A(); // object of type A

B b = new B(); // object of type B

C c = new C(); // object of type C

A r; // obtain a reference of type A

r = a; // r refers to an A object

r.callme(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme

r = c; // r refers to a C object

r.callme(); // calls C's version of callme

The output from the program is shown here:

Inside A’s callme method

Inside B’s callme method

Inside C’s callme method

44]What is inheritance? List types of inheritance and explain single level


inheritance with example.

Inheritance in Java is a mechanism in which one object acquires all the

properties and behaviors of a parent object. The idea behind inheritance is that

we can create new classes that are built upon existing classes. When we

inherit from an existing class, we can reuse methods and fields of the parent

class.

syntax -

class Subclass-name extends Superclass-name

//methods and fields

A class which is inherited is called a parent or superclass, and the new class is

called child or subclass.

Types of inheritance

1)Single inheritance

2)Multilevel inheritance

3)Multiple inheritance

4)Hierarchical inheritance

Single level Inheritance

In single inheritance, subclasses inherit the features of one superclass. In

image below, the class A serves as a base class for the derived class B.
For example

class one

int v1=10;

void method1()

System.out.println("we are in method 1");

class two extends one

void method2()

System.out.println("v1="+v1);

System.out.println("we are in method 2");

}
}

class singleinherit

public static void main(String[] args)

two t = new two();

t.method1();

t.method2();

Output:

we are in method 1

v1=10;

we are in method 2

45]

import java.io.*;
interface sport

int sport_wt=5 ;

class student

String name;

int roll_no,marks;

public void getdata()

DataInputStream d=new DataInputStream(System.in);

try

System.out.println("enter the name");

name=d.readLine();

System.out.println("enter the roll_no");

roll_no=Integer.parseInt(d.readLine());

System.out.println("enter the marks");

marks=Integer.parseInt(d.readLine());

catch(Exception e)

System.out.println(“input output error”);

System.out.println(" ");

System.out.println("name="+name);
System.out.println("roll no="+roll_no);

System.out.println("marks1="+marks);

class result extends student implements sport

int total;

public void get_total()

super.getdata();

total=sport_wt+super.marks;

public void display()

System.out.println("total marks="+total);

public static void main(String args[])

result r=new result();

r.get_total();

r.display();

Output:

enter the name

abc

enter the roll_no


11

enter the marks

200

name=abc

roll no=11

marks1=200

total marks=205

46]Enlist Build-in packages of java, explain any four in details with

example.

Package in Java is a mechanism to encapsulate a group of classes,

sub packages and interfaces. There are two types of packages.

1. Built in packages

2. User defined packages- are packages defined by user.

Built in packages are part of java API. Some of the built in packages

in java are:

java.io-this package contains classes and interfaces for performing

input and output operations and also serialization.

Eg of classes/interfaces:

BufferedReader, BufferedWriter, Serializable, InputStream,

OutputStream

java.util-contains utility classes/interfaces for implementing data

structures, and other utility class like Date.

Eg: Vector, Scanner, ArrayList, Date

java.net-this package consists of classes that support networking

operations.

Eg: URL, URLConnection, Socket,ServerSocket


java.awt-this package contains a large number of classes used for

GUI.

Eg: Graphics, Panel, Container

java.applet-this package contains classes/interfaces that are used to

create and use applets

Eg: Applet,AppletContext,AudioClip

java.lang-this package is automatically imported and contains

language support classes like String, Thread,Math

47]
System.out.println("Customer name is "+name);

public static void main(String ar[]) {

try {

String b,a,n;

int no;

BufferedReader br = new BufferedReader(new

InputStreamReader(System.in));

System.out.println("Enter bank name");

b = br.readLine();

System.out.println("Enter address");

a = br.readLine();

System.out.println("Enter customer name");

n = br.readLine();

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

no = Integer.parseInt(br.readLine());

Passbook p = new Passbook();

p.input(b,a,no,n);

p.display();

} catch(Exception e) {

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

You might also like