CH-3 Java_notes
CH-3 Java_notes
_________________________________________________________________
Content
3.4 Package: Define package, type of package naming and creating packages,
accessing package, import statement. Static import, adding class and
interface to a package.
Inheritance
Inheritance can be defined as the process where one class acquires the
properties (methods and fields) of another.
The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
Super Class: The class whose features are inherited is known as superclass
(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class. By
doing this, we are reusing the fields and methods of the existing class.
Page 1
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is
the syntax of extends keyword.
Syntax
class super_class_name
{
------
------
}
class Sub_class_name extends super_class_name
{
------
------
}
Page 2
Single Inheritance
When a subclass is derived simply from its parent’s class then this mechanism
is known as single inheritance.
In this type there is only one child class and one parent class.
Example 1)
class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation
{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[])
{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
Page 3
}
}
The Superclass reference variable can hold the subclass object, but using that
variable you can access only the members of the superclass, so to access the
members of both classes it is recommended to always create reference variable to
the subclass.
If you consider the above program, you can instantiate the class as given below. But
using the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
Example 2)
Page 4
import java.lang.*;
class sphere
{
int r;
float pi;
sphere(int r, float pi) //super class constructor
{
this.r=r;
this.pi=pi;
}
void volume() //method to display volume of sphere
{
float v=(4*pi*r*r)/3;
System.out.println("Volume of Sphere="+v);
}
}
class hemisphere extends sphere //subclass defined
{
int a;
hemisphere(int r, float pi, int a)
{
super(r,pi);
this.a=a;
}
void volume() //method to display volume of hemisphere
{
super.volume();
float v=(a*pi*r*r*r)/3;
System.out.println("Volume of Hemisphere="+v);
}
}
class volume
{
public static void main(String args[]) //main method
{
hemisphere h=new hemisphere(12, 3.14f, 2);
Page 5
h.volume();
}
}
Output:
Volume of Sphere=602.88
Volume of Hemisphere=3617.28
___________________________________________________________________
Example 3:
class person
{
String name;
int age;
void getdata(String n, int a)
{
name=n;
age=a;
}
void putdata()
{
System.out.println("Employee Details: ");
System.out.println("Employee Name: "+name);
System.out.println("Employee Age: "+age);
}
}
class emp extends person
{
String emp_desig;
int emp_sal;
Page 6
void getdata(String n, int a, String e, int s)
{
super.getdata(n,a);
emp_desig=e;
emp_sal=s;
}
void putdata()
{
super.putdata();
System.out.println("Employee's Designation: "+emp_desig);
System.out.println("Employee's Salary; Rs. "+emp_sal);
}
}
class emp1
{
public static void main(String args[])
{
emp e1=new emp();
e1.getdata("vijay",30,"Manager",50000);
e1.putdata();
}
}
Output:
Employee Details:
Employee Name: vijay
Employee Age: 30
Employee's Designation: Manager
Employee's Salary; Rs. 50000
Multilevel Inheritance
When a class is derived from already derived class then this mechanism is
known as multilevel inheritance.
The derived class is called as subclass or child class for its parents class and
this parent class work as child class for its just above parent class.
Page 7
Multilevel inheritance can go up to any level
___________________________________________________________________
1. e.g.
import java.lang.*;
class Square //super class
{
int length;
Square(int x)
{
length=x;
}
void area() //method to calculate area of square
{
int area=length*length;
System.out.println("Area of Square="+area);
}
}
class Rectangle extends Square //inherit class rectanglefrom class square
{
int breadth;
Rectangle(int x, int y)
{
super(x); //calling super class constructor
breadth=y;
}
void rectArea()
{
int area1=length*breadth;
Page 8
System.out.println("Area of Rectangle="+area1);
}
}
class Box extends Rectangle //inherit class Box from class Rectangle
{
int height;
Box(int x, int y, int z) //calling rectangle class constructor
{
super(x,y);
height=z; }
void volume()//method to display volume of box
{
int volume=length*breadth*height;
System.out.println("Volume of Box="+volume);
}
}
class Shape
{
public static void main(String args[]) //main method
{
Box b=new Box(10,20,30);
//creating object of Box class
b.volume();
b.rectArea();
b.area();
}
}
Output:
Volume of Box=6000
Area of Rectangle=200
Area of Square=100
____________________________________________________________
2. e.g.
Page 9
class account
{
String custname;
int accno;
void getdata(String n, int a)
{
custname=n;
accno=a;
}
void putdata()
{
System.out.println("Customers Account Details\n");
System.out.println("Customers Name: "+custname);
System.out.println("Customers Account Number: "+accno);
}
}
class savingacc extends account
{
int minbal;
int savbal;
void getdata(String n, int a, int m, int s)
{
super.getdata(n,a);
minbal=m;
savbal=s;
}
Page 10
void putdata()
{
super.putdata();
System.out.println("Minimum Balance: "+minbal);
System.out.println("Saving Balance: "+savbal);
}
}
class accdetail extends savingacc
{
int deposits;
int withdrawal;
void getdata(String n, int a, int m, int s, int d, int w)
{
super.getdata(n,a,m,s);
deposits=d;
withdrawal=w;
}
void putdata()
{
super.putdata();
System.out.println("Deposit: "+deposits);
System.out.println("Withdrawal Amount: "+withdrawal);
}
}
class acc
{
public static void main(String args[])
{
accdetail a1=new accdetail();
a1.getdata("Vijay",123,500,10000,5000,2500);
a1.putdata();
}
}
Output:
Customers Account Details
Customers Name: Vijay
Page 11
Customers Account Number: 123
Minimum Balance: 500
Saving Balance: 10000
Deposit: 5000
Withdrawal Amount: 2500
___________________________________________________________________
Hierarchical Inheritance
import java.io.*;
abstract class shape
{
float dim1,dim2;
void getdata()
{
DataInputStream d=new DataInputStream(System.in);
try
{
System.out.println("Enter the value of Dimension1: ");
dim1=Float.parseFloat(d.readLine());
System.out.println("Enter the value of Dimension2: ");
dim2=Float.parseFloat(d.readLine());
}
catch(Exception e)
Page 12
{
System.out.println("General Error"+e);
}
}
void disp()
{
System.out.println("Dimension1= "+dim1);
System.out.println("Dimension2= "+dim2);
}
abstract void area();
}
class rectangle extends shape
{
double area1;
void getd()
{
super.getdata();
}
void area()
{
area1=dim1*dim2;
System.out.println("The Area of Rectangle is: "+area1);
}
}
class triangle extends shape
{
double area1;
void getd()
{
super.getdata();
}
void area()
{
area1=(0.5*dim1*dim2);
System.out.println("The Area of Triangle is: "+area1);
}
Page 13
}
class methodover1
{
public static void main(String args[])
{
rectangle r=new rectangle();
System.out.println("For Rectangle");
r.getd();
r.disp();
r.area();
triangle t=new triangle();
t.getd();
t.disp();
t.area();
}
}
Output:
For Rectangle
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 5.0
Dimension2= 6.0
The Area of Rectangle is: 30.0
Enter the value of Dimension1:
Enter the value of Dimension2:
Dimension1= 6.0
Dimension2= 7.0
The Area of Triangle is: 21.0
Example 2)
class A
{
public void methodA()
{
Page 14
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class H_inheritance
{
public static void main(String args[])
{
B objb = new B();
C objc = new C();
D objd = new D();
//All classes can access the method of class A
objb.methodA();
objc.methodA();
objd.methodA();
Page 15
objb.methodB();
objc.methodC();
objd.methodD();
//objc.methodB(); //error
}
}
___________________________________________________________________
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
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.
Method overloading allows user to achieve the compile time polymorphism.
Suppose, you have to perform the addition of given numbers but there can be
any number of arguments (let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods sum2num(int,
int) and sum3num(int, int, int) for two and three parameters respectively.
However, other programmers, as well as you in the future may get confused as
the behavior of both methods are the same but they differ by name.
The better way to accomplish this task is by overloading methods. And,
depending upon the argument passed, one of the overloaded methods is
called. This helps to increase the readability of the program.
Syntax:
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
For e.g. 1
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
{
Page 17
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));
}
}
For e.g. 2
class Overload
{
void test (int a)
{
System.out.println(“a”+a);
}
void test (int a, int b)
{
System.out.println(“a & b”+a “and” +b);
}
double test(double a)
{
System.out.println(“Double a” +a);
Return a*a;
}
}
class demo
{
public static void main(String args[])
{
Overload obj = new Overload();
double result;
obj.test(10);
obj.test(10, 20);
result= obj.test(5.5);
Page 18
System.out.println(“result is:”+result);
}
}
{
System.out.println("Addition of 2 numbers: " + (a+b));
}
Example:
class MethodOverloading1 {
Page 19
// this method accepts String object
private static void display(String a){
System.out.println("DisplayString object.");
}
Example:
public class OverloadingExample2
{
private int rollNum;
OverloadingExample2() //dc
{
rollNum =100;
}
OverloadingExample2(int rnum)
{
this();
/*this() is used for calling the default
* constructor from parameterized constructor.
* It should always be the first statement
* inside constructor body.
*/
rollNum = rollNum+ rnum;
}
public int getRollNum()
{
return rollNum;
}
public void setRollNum(int rollNum)
Page 20
{
this.rollNum = rollNum;
}
public static void main(String args[])
{
OverloadingExample2 obj = new OverloadingExample2(15);
System.out.println(obj.getRollNum());
}
}
As you can see in the above program that we called the parameterized
constructor during object creation. Since we have this() placed in
parameterized constructor, the default constructor got invoked from it and
initialized the variable rollNum.
Example:
public class OverloadingExample3
{
private int rollNum;
OverloadingExample3()
{
rollNum =100;
}
OverloadingExample3(int rnum)
{
Super Keyword:
The super keyword in java is a reference variable that is used to refer parent
class objects. The keyword “super” came into the picture with the concept of
Inheritance. It is majorly used in the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and
base class has same data members. In that case there is a possibility of
ambiguity for the JVM. We can understand it more clearly using this code
snippet:
Page 22
}
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:
Maximum Speed: 120
In the above example, both base class and subclass have a member
maxSpeed. We could access maxSpeed of base class in subclass using super
keyword.
2. Use of super with methods: This is used when we want to call parent class
method. So whenever a parent and child class have same named methods
then to resolve ambiguity we use super keyword. This code snippet helps to
understand the said usage of super keyword.
Page 23
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
class Test
{
public static void main(String args[])
{
Student s = new Student();
Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message()
then, the current class message() is invoked but with the use of super
keyword, message() of superclass could also be invoked.
3. Use of super with constructors: super keyword can also be used to access
the parent class constructor. One more important thing is that, ‘’super’ can
call both parametric as well as non-parametric constructors depending upon
the situation. To access the method of parent class when child class has
overridden that method.
Page 24
/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:
Person class Constructor
Student class Constructor
In the above example we have called the superclass constructor using
keyword ‘super’ via subclass constructor.
Method Overriding
Page 25
There may be situation when we want an object to respond to the same
method but have different behavior when that method is called.
This is possible by defining a method in the subclass that has the same name,
same arguments and same return type as a method in the superclass.
Then, when that method is called, the method defined in the subclass is
invoked and executed instead of the one in the superclass. This is known as
overriding.
Method overriding is one of the way by which java achieve Run Time
Polymorphism.
In overriding return types and constructor parameters of method should
match.
Page 26
{
public static void main(String arg[])
{
Sub s1= new Sub(100,200);
s1.display();
}
}
class A
{
int i;
A(int a, int b)
{
i=a+b;
}
void add()
{
System.out.println(“Sum of a & b is=” +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 & c”+j);
}
Page 27
}
class MethodOverride
{
public static void main(String args[])
{
B b=new B(10,20,30);
b.add();
}
}
Example:
import java.lang.*;
class A
{
void show()
{
System.out.println("in show of A");
}
}
class B extends A
{
Page 28
void show()
{
System.out.println("in show of B");
}
}
class C extends B
{
void show()
{
System.out.println("in show of C");
}
}
class DynaMethod
{
public static void main(String args[])
{
A a = new A(); // object of class A
B b = new B(); // object of class B
C c = new C(); // object of class C
A r; // obtain a reference of type A
r = a; //r refer to object of A
r.show(); // call show() of A
r = b; //r refer to object of B
r.show(); // call show() of B
r = c; //r refer to object of C
r.show(); // call show() of C
}
}
Output:
in show of A
in show of B
in show of C
Page 29
A.
Page 30
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.
Page 31
In Java, the final keyword is used to denote constants. It can be used with
variables, methods, and classes.
Once any entity (variable, method or class) is declared final, it can be assigned
only once. That is,
the final variable cannot be reinitialized with another value
the final method cannot be overridden
the final class cannot be extended
Java final Variable
In Java, we cannot change the value of a final variable.
class Main {
public static void main(String[] args) {
Page 32
class Main extends FinalDemo {
// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}
Page 33
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final class named FinalClass. Here,
we have tried to inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following
message.
cannot inherit from final FinalClass
class Main extends FinalClass { }
Abstract Class
Example:1
Page 34
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();
}
}
Output :
show method is not abstract
inside class B
Example: 2
Page 35
abstract class Employee
{
int empid;
String empname;
Employee(int e,String n)
{
empid=e;
empname=n;
}
void display()
{
System.out.println("Employee ID is: "+empid);
System.out.println("Employee name is: "+empname);
}
}
class Manager extends Employee
{
int mid;
String mname;
int phno;
Manager(int e,String n,int m,String mn,int p)
{
super(e,n);
mid=m;
mname=mn;
phno=p;
Page 36
}
void displaym()
{
super.display();
System.out.println("Manager ID is: "+mid);
System.out.println("Manager name is: "+mname);
System.out.println("Phone no is: "+phno);
}
}
class Worker extends Employee
{
int wid;
String wname;
double whours;
Worker(int e,String n,int w,String wn,double wh)
{
super(e,n);
wid=w;
wname=wn;
whours=wh;
}
void displayw()
{
super.display();
System.out.println("worker ID is: "+wid);
System.out.println("worker name is: "+wname);
System.out.println("Working hours= "+whours);
}
}
class Company
{
public static void main(String arg[])
{
Manager m1=new Manager(11,"Neel",121,"Sameer",123456);
m1.displaym();
Page 37
Worker w1=new Worker(22,"Ishan",222,"Priyank",6);
w1.displayw();
}
}
Example: 3
import java.io.*;
abstract class shape
{
float dim1,dim2;
void getdata ()throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter dimension 1");
dim1 =Float.parseFloat(br.readLine());
System.out.println("Enter dimension 2");
dim2=Float.parseFloat(br.readLine());
}
void disp()
{
System.out.println("dimension 1="+dim1);
System.out.println("dimension="+dim2);
}
abstract void area();
}
class Rectangle extends shape
Page 38
{
double area1;
float dim1,dim2;
void getd() throws IOException
{
super.getdata();
}
void area()
{
area1=dim1*dim2;
System.out.println("area of rectangle is"+area1);
}
}
class triangle extends shape
{
double area;
float dim1,dim2;
void getd1() throws IOException
{
super.getdata();
}
void area()
{
area=(0.5*dim1*dim2);
System.out.println("area of triangle is"+area );
}
}
class abs
{
public static void main(String args[]) throws IOException
{
Rectangle r =new Rectangle();
System.out.println("for Rectangle:");
r.getd();
r.disp();
Page 39
r.area();
System.out.println("for triangle:");
triangle t =new triangle ();
t.getd1();
t.disp();
t.area();
}
}
Syntax:-
abstract class Employee
{
abstract void work();
}
o If a class extends the abstract class, it must also implement at least one of the
abstract method.
o An abstract class can contain the main method and the final method.
}
class Honda extends Vehicle
{
void bike() //override
{
System.out.println("Bike is running");
}
}
public class AbstractExample1
{
public static void main(String[] args) {
Honda obj=new Honda();
obj.bike();
}
}
Example:
//Abstract class containing the abstract and non-abstract method
abstract class Vehicle
{
abstract void bike();
void car()
{
System.out.println("Car is running");
}
Page 41
}
class Honda extends Vehicle
{
//Override
void bike() {
System.out.println("Bike is running");
}
}
Example:
//Abstract class containing the constructor
abstract class Vehicle
{
String msg;
Vehicle(String msg)
{
this.msg=msg;
}
void display()
{
System.out.println(msg);
}
Page 42
}
class Honda extends Vehicle
{
Honda(String msg)
{
super(msg);
//super.display();
}
}
Example:
//Abstract class containing overloaded abstract methods
abstract class Vehicle
{
}
class Honda extends Vehicle
{
Page 43
//override zero parameter
void display()
{
System.out.println(msg);
}
}
public class AbstractExample4 {
Example:
//Inner abstract class
class Vehicle
{
abstract class Car
{
abstract void display();
}
Page 44
void display()
{
System.out.println("inner abstract class is invoked");
}
}
}
public class AbstractExample5 {
public static void main(String[] args) {
Vehicle obj=new Vehicle();
Vehicle.Car c=obj.new Honda();
c.display();
}
}
Static Members
When a number of objects are created from the same class, each instance has
its own copy of class variables. But this is not the case when it is declared as
static.
Static method or a variable is not attached to a particular object, but rather to
the class as a whole. They are allocated when the class is loaded.
If some objects have some variables which are common, then these variables
or methods must be declared static.
To create a static variable, precede its declaration with keyword static. Static
variables
c c n n hhhn need not be called on any object.
Example:
int a; // normal variable
static int a; //static variable
class s
{
int a,b;
static int c;
}
class statictest
{
public static void main(String args[])
Page 45
{
s ob1=new s();
s ob2=new s();
s ob3=new s();
}
}
In above program variable a and b are declared as int variable whereas the variable
c is declared as static variable. Static variable will be common between all the
objects.
When we accessing variable as ‘a’ we cannot access it directly without the reference
of the object because ‘a’ exist in all three objects. So to access the value of ‘a’ we
must link it with the name of the object. But the ‘c’ is static variable and it is
common between all the objects so we can access it directly. But when we are
accessing it outside the class in which it is declared, we must link it with the name of
the class i.e. with S as S.c=20;
Output:
from m1
Static blocks
If you need to do computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
Consider the following java program demonstrating use of static blocks.
// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
Page 47
}
Output:
Static block initialized.
from main
Value of a : 10
Value of b : 40
Static variables
When a variable is declared as static, then a single copy of variable is created and
shared among all objects at class level. Static variables are, essentially, global
variables. All instances of the class share the same static variable.
Important points for static variables: -
We can create static variables at class-level only.
static block and static variables are executed in order they are present in a
program.
Below is the java program to demonstrate that static block and static variables are
executed in order they are present in a program.
// static block
static {
System.out.println("Inside static block");
}
// static method
static int m1() {
System.out.println("from m1");
return 20;
}
Page 48
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
Output:
from m1
Inside static block
Value of a : 20
from main
Static methods
When a method is declared with static keyword, it is known as static method. The
most common example of a static method is main( ) method. As discussed above,
Any static member can be accessed before any objects of its class are created, and
without reference to any object. Methods declared as static have several restrictions:
They can only directly call other static methods.
They can only directly access static data.
They cannot refer to this or super in any way.
Below is the java program to demonstrate restrictions on static methods.
// instance variable
int b = 20;
// static method
static void m1()
{
a = 20;
System.out.println("from m1");
Page 49
// Cannot use super in a static context
System.out.println(super.a); // compiler error
}
// instance method
void m2()
{
System.out.println("from m2");
}
3.2 Interfaces
Page 50
The general from of interface is
access interface interface_name
{
variable declaration;
method declaration;
}
Access is either public or not used when no access specifier is included, then
default access result and interface is only available to other member of the
package in which it is declared.
For e.g.-
public interface IF4IA
{
String Lecture=”JPR”;
int benches=35;
void display();
}
Implementing Interface
A class can only inherit from one super class. However, a class may implement
several interfaces.
To declare a class that implements an interface, you need to include
‘implements’ clause in the class declaration.
Your class can implements keyword is followed by a ‘comma separated list’ of
the interface implemented by a class.
Syntax:- class class_name implements interface
{
//body
}
OR
class class_name extends class_name implemnts interface 1,2
For e.g.-
inteface shape
{
public String baseclass="Shape";
Page 51
public void draw();
}
class circle implements shape
{
public void draw()
{
System.out.println("Circle drawn here");
}
}
An interface can use to declare set of constants that can be used in different
classes. This is similar to creating header files in c++ to contain a large no. of
constants.
Such interface does not contain methods, there is no need to worry about
implementing methods.
All variable declared in interface must be constant.
For e.g._
interface one
{
int x=12;
}
interface two
{
int y=10;
void display();
}
class demo implemets one, two
{
int a=x;
int b=y;
public viod display()
{
System.out.println("x in interfece one" +x);
Page 52
System.out.println("y in interfece one" +y);
System.out.println("x & y"+(x+y));
}
public void disp()
{
System.out.println("Value access from interface one:" +a);
System.out.println("Value access from interface two:" +b);
}
}
class multipleinterface
{
public static void main(String args[])
{
demo d= new demo();
d.display();
d.disp();
}
}
Extending Interface
An interface can extend another interface, similarly to the way that a class can
extend another class.
The extends keywords is used to extend an interface, and the child interface
inheritas the methods of the parent interface.
Syntax: -
interface class2 extends class1
{
//body
}
For e.g.:-
inteface A
{
void show();
}
interface B extends A
Page 53
{
void display();
}
class C implements B
public void show()
{
System.out.println("calling interface A");
}
public void display()
{
System.out.println("calling interface B");
}
public void disp()
{
System.out.println("class C is working");
}
}
class D
{
Public static void main(String a[])
{
C object=new C();
object.show();
object.display();
object.disp();
}}
How to achieve multiple inheritance?
It is type of interface where a derived class may have more than one parent
class.
It is not possible in case of Java as you cannot have two parent classes at the
parent level, instead there can be one class and one interface at parent level
to achieve multiple inheritance.
Interface is similar to classes but can contain final variable and abstract
methods. Interfaces can be implemented to a derived class.
For e.g : -
Page 54
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);
Page 55
r.disp();
}
}
___________________________________________________________________
Example No. 2
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);
}
}
class Salary extends Employee implements Gross
{
double HRA;
Page 56
Salary(String n, double b, double h)
{
super(n,b);
HRA=h;
}
void disp_sal()
{
Super.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();
}
}
Nested Interface
An interface which is declared within another interface or class is known as
nested interface.
The nested interface is used to group related interfaces so that they can be
easy to maintain.
The nested interface must be referred by the outer interface or class.
A nested interface can be declared as public, private or protected.
Syntax: -
1. Nested interface declared within interface
interface interface_name
Page 57
{
inetrface nested_interface_name
{
-------
-------
}
}
For E.g.
interface display
{
void show();
interface message
{
void msg();
}
}
class test implemets display.message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String a[])
{
display.message message= new test();
message.msg();
}
}
___________________________________________________________________
2. Interface within class
interface class_name
{
inetrface nested_interface_name
{
-------
Page 58
-------
}
}
For E.g
class Test
{
interface Yes //nested interface
{
void show();
}
}
class A_nested_interface
{
public static void main(String[] args)
{
Test.Yes obj;
Testing t = new Testing();
obj=t;//reference
obj.show();
}
}
Example 2:
// Java program to demonstrate working of
Page 59
// interface inside another interface.
interface Test
{
interface Yes
{ int a=20;
public void show();
}
}
class A_nested_inteface_1
{
public static void main(String[] args)
{
Test.Yes obj; //creating varible on interface
Testing t = new Testing();
obj = t;
obj.show();
}
}
Class interface
Classes are not used to implement The interfaces are used in java to
multiple inheritance. implementing the concept of multiple
inheritance.
The member of a class can be constant The members of an interface are
or variables. always declared as constant i.e. their
Page 60
values are final.
The class definition can contain the The methods in an interface are
code for each of its methods. That is abstract in nature. I.e. there is no code
the methods can be abstract or non- associated with them. It is defined by
abstract. the class that implements the
interface.
Class contains executable code. Interface contains no executable code.
Memory is allocated for the classes. We are not allocating the memory for
the interfaces.
We can create object of class. We can ‘t creates object of interface.
Classes can be instantiated by Interface cannot be used to declare
declaring objects. objects. It can only be inherited by a
class.
Classes can use various access Interface can only use the public
specifiers like public, private or access specifier.
protected.
Class contains constructors. An interface does not contain any
constructor.
Classes are always extended. Interfaces are always implemented.
A class can extend only one class (no Interfaces can extend one or more
multiple inheritance), but it can other interfaces. Interfaces cannot
implement many interfaces. extend a class, or implement a class or
interface.
An abstract class is fast. An interface requires more time to find
the actual method in the
corresponding classes.
Package
Package is nothing more than the way we organize files into different
directories according to their functionality, usability as well as category they
should belongs to.
Packaging also helps us to avoid class name collision when we use the same
class name as that of others.
Packages act as containers for classes.
Page 61
Syntax: -
package pakage_name;
For e.g.
package A;
class ABC
{
------
------
}
Types of packages: -
1. Java API Package
Naming Convention:
Package names are written in all lower case to avoid conflict with the names of
classes or interfaces.
All class name begins with an uppercase letter and method name begin with
lowercase letters
Page 62
For e.g. :- double x=java lang.Math.sqrt(x); where lang is package name and
Math is class name
Creating Package:
Declare a package at beginning of a file using syntax: - package
package_name;
Define the class that is to be put inside the package and declare it as public.
Create subdirectory under the directory where the main source files are
stored.
Store the listing as classname.java files in the subdirectory created.
Compile the file, this creates .class file in the subdirectory.
Accessing Package:
Package can be accessed using keyword import.
There are 2 ways to access java system packages:
o Package can be imported using import keyword and the wild card(*) but
drawback of this shortcut approach is that it is difficult to determine
from which package a particular member name.
Syntax: import package_name.*;
For e.g. import java.lang.*;
o The package can be accessed by using dot(.) operator and can be
terminated using semicolon(;)
Syntax: import package1.package2.classname;
For e.g. VP.IF.IF4I.IF4IA
Page 63
System.out.println("shreyas");
}
(main code)
import myInstitute.*;
public class demo
{
public static void main(String a[])
{
department d=new department();
d.display();
}
}
Example 2:
Develop a program which consist of the package named let_me_calculate
with a class named calculator and a method name add to add two integer
no. import let_me_calculate package in anather program to add two no.
package let_me_calculate;
public class calculate
{
public void add()
{
int a=20;
int b=30;
int c=a+b;
System.out.println("addition="+c);
}
}
import let_me_calculate.*;
public class calculator
{
public static void main(String arg[])
{
calculate c=new calculate();
Page 64
c.add();
}
}
‘Import’ Statement: -
i) The import keyword is used to import built-in packages & user defined packages.
So that your class can refer a class that is in another package by directly using its
name.
ii) There are different ways to refer to a class that is present in different packages:-
Page 65
import static package.classname static membername;
For eg:-
import static java.lang.Math.sqrt;
2. Import all static members a class.
Syntax:
Import static package.classname.*;
For Eg:-
Adding class to a package
Structure:-
Package p1
public class A
{
/body of class
}
Create a file outside of package which consists of main method
import p1.*;
Class B
{
public static void main (String args[])
{
// create object of class which is in package
}
}
Example: //without using static import
class Geeks
{
public static void main(String[] args)
{
System.out.println(Math.sqrt(4));
System.out.println(Math.pow(2, 2));
System.out.println(Math.abs(6.3));
}
}
Page 66
Example: // using static import
Page 67