JPR Ch3 CO 4I Notes
JPR Ch3 CO 4I Notes
Java Programming
As per MSBTE ‘I’ Scheme Syllabus
JPR-22412
Unit- III
Inheritance, Interface and Package
Total Marks- 12
}
class TestInheritance
{
public static void main(String args[])
{
Student s=new student();
s.show();
d.display();
}
}
Output-
This is student
This is teacher
Class: Person,
name , age
Class: employee,
emp_designation,
emp_salary
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 args[])
{
employee e=new employee();
e.accept("ramesh",35);
e.display();
e.accept_emp("lecturer",35000.78f);
e.emp_dis();
}
}
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);
}
}
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);
}
}
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));
}
}
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
class Student
{
int id;
String name;
int age;
//creating two arg constructor
Student(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
Program 4. 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);
}
}
}
Example:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
execute based on the type of object it refer to. In simple words the type of object which it
referred determines which version of overridden method will be called.
Example
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
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);
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;
}
}
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 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
}
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.
Q. 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
Abstract methods, similar to methods within an interface, are declared without any
implementation. They are declared with the purpose of having the child class provide
implementation. They must be declared within an abstract class.
A class declared abstract may or may not include abstract methods. They are created
with the purpose of being a super class.
Syntax
Abstract classes and methods are declared with the 'abstract' keyword. Abstract classes
can only be extended, and cannot be directly instantiated.
Abstract classes provide a little more than interfaces. Interfaces do not include fields
and super class methods that get inherited, whereas abstract classes do. This means that an
abstract class is more closely related to a class which extends it, than an interface is to a class
that implements it.
Example
Example
class VariableDemo
{
Output:
Interface:-
➢ Defining Interfaces:-
Interface is also known as kind of a class. 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);
Where,
access is either public or not used.
‘interface’ is the java keyword and “InterfaceName” is nay valid java variables.
Variables- of interface are explicitly declared final and static. This means that the
implementing class cannot change them. They must be initialized with constant value.
Methods- The methods declared in interfaces are abstract, there can be no default
implementation of any method specified within an interface.
• 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:
Class Interface
It has instance variable. It has final variable.
It has non abstract method. It has by default abstract method.
We can create object of class. We can„t create object of interface.
Class has the access specifiers like public,
Interface has only public access specifier
private, and protected.
Classes are always extended. Interfaces are always implemented.
The memory is allocated for the classes. We are not allocating the memory for the interfaces.
Interface was introduced for the concept of multiple
Multiple inheritance is not possible with classes
inheritance
interface Example
class Example
{
{
int x =5;
void method1()
void method1();
{
void method2();
Body
}
}
void method2()
{
body
}
}
➢ Extending interfaces:-
Like classes, Interfaces can also be extended. That is an interface can be sub-interfaced
from other interfaces. The new sub-interfaced will inherit all the members of the sub-interfaces in
the manner similar to subclasses.
interface A extends B A
{
body of A.
B
}
• We can put all the constant in one interface and the methods in the other. This will enable
us to use the constants in the classes where the methods are not required.
E.g
E.g
interface X
{
int cost=100; X Y
String name=”book”;
}
interface Y Z
{
void display();
}
interface Z extends X , Y
{
--------
}
➢ Implementing interfaces:-
Interfaces are used as “super classes” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface.
This is done as follows.
E.g.
class A implements B
{
Body of class A;
}
E.g.
class A extends B implements X,Y, .......
{
Body of class A;
}
Interface A class A D
Implementation extension
Class C class C
(a) (b)
class InterfaceDemo
{
Public static void main(String args[ ])
{
Rectangle r = new Rectangle( );
Circle c = new Circle( );
Area a ; // interface object
a = r;
System.out.println(“Area of Rectangle=” +a.Cal(10,20));
a = c;
System.out.println(“Area of Circle=” +a.Cal(10, 0));
}
}
Output :-
C:\java\jdk1.7.0\bin> javac InterfaceDemo.java
C:\java\jdk1.7.0\bin> java InterfaceDemo
Area of Rectangle=200
Area of Circle=314
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;
}
}
int t=m1+m2+sport_wt;
System.out.println("total : "+t);
}
class Demo
{
public static void main(String args[])
{
Result r= new Result(101,"abc",75,75);
r.disp();
}
}
Interfaces can be used to declare a set of constant that can be used in different classes. This
is similar to creating header files in C++ to contain a large no. of constants. The constant values
will be available to any class that implements the interface. The values can be used in declaration,
or anywhere we can use a final value.
E.g.
interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void method_B(int s)
{
-------
if(s<n)
}
}
➢ Nesting of inheritances:-
Interfaces can be nested similar to a class. An interface can be nested within a class and
another interface.
An interface can be declared inside a class body or interface body is called as nesting of
interfaces. The nested interface cannot be accessed directly. To access nested interface, it must be
referred by the outer interface or class.
• 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.
Class:salary
disp_sal ( ), HRA
interface Gross
{
double TA=800.0;
double DA=3500;
void gross_sal();
}
class Employee
{
String name;
double basic_sal;
Employee(String n, double b)
{
name=n; basic_sal=b;
}
void display()
{
System.out.println("Name of Employee :"+name);
System.out.println("Basic Salary of Employee :"+basic_sal);
}
}
3.2 Packages-
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.
We can define classes inside a package that are not accessible by code outside that package.
We can also define class members that are only exposed to members of the same package.
The java API provides a no. of classes grouped into different packages according to their
functionality.
Package
Description (Use of Package)
Name
Language support classes. These are classes that java compiler itself uses and
java.lang therefore they are automatically imported. They include classes for primitive
types, strings, math functions, threads and exceptions.
java .util Language utility classes such as vectors, hash tables, random numbers, date etc.
Input/output support classes. They provide facilities for the input and output of
java.io
data
Set of classes for implementing graphical user interface. They include classes for
java.awt
windows, buttons, lists, menus and so on.
Classes for networking. They include classes for communicating with local
java.net
computers as well as with internet servers.
• Naming Conventions:-
2) double x= java.lang.Math.sqrt(a);
lang- package name, math- class name, sqrt- method name
1) Declare a package at the beginning of the file using the following form.
package package_name
e.g.
package pkg; - name of package
package is the java keyword with the name of package. This must be the first
statement in java source file.
2) Define a class which is to be put in the package and declare it public like following way.
Package first_package;
Public class first_class
{
-----
Body of class;
}
3) Create a sub-directory under the directory where the main source files are stored.
5) Compile the source file. This creates .class file is the sub-directory. The .class file
must be located in the package and this directory should be a sub-directory where
classes that will import the package are located.
package pkg;
Here, pkg is the name of the package
e.g : 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.
➢ Accessing a package:-
Syntax:
import pkg1[.pkg2].(classname|*);
Here, “pkg1” is the name of the top level package. “pkg2” is the name of package
is inside the package1 and so on.
import packagename.*;
Access Modifier
Public Private Protected
Access Location
Same class Yes Yes Yes
Subclass in same package Yes No Yes
Other classes in same package Yes No Yes
Subclass in other packages Yes No Yes
Non subclasses in other packages Yes No No
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();
}
}
➢ Que:- 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);
}
}
Consider the we have package ‘P’ and suppose class B is to be added to following
package.
Package P;
{
Public class X;
{
//body of X;
}
}
Package P1;
Before the class definition as follows
Package P1;
Public class B
{
// Body of B
}
4) Compile B.java file. This will create B.class file and place it in the directory P1.
Now, the package “P2” contains both the classes A and B. So to import both classes use
import P1.*
18) What is interface ? How it is different from class ? With suitable program explain
the use of interface.
19) What is package ? How to create package ? Explain with suitable example.
20) Write a program to implement following hierarchy
Class:salary
disp_sal ( ), HRA