Professional Documents
Culture Documents
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 2
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
e.get(15,"Disha");
e.input(89.25);
e.output();
}
}
Output: Roll Number : 15
Name : Disha
Percentage: 89.25
// WAP to implement Single Inheritance, Use Constructors.
class Student
{
int rollno;
String name;
Student(int r, String n)
{
rollno = r;
name = n;
}
void put()
{
System.out.println("Roll Number : "+rollno);
System.out.println("Name : "+name);
}
}
class Exam extends Student
{
double percent;
Exam(int r, String n, double p)
{
super(r, n);
percent = p;
}
void output()
{
put();
System.out.println("Percentage : "+percent);
}
}
class Inheritance2
{
public static void main(String args[])
{
Exam e = new Exam(15, “Disha”, 89.25);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 3
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
e.output();
}
}
Output: Roll Number : 15
Name : Disha
Percentage: 89.25
Subclass Constructor:
A subclass constructor is used to construct the instance variables of both the subclass and the
superclass. The subclass constructor uses the keyword super to invoke the constructor method of
the superclass. The keyword super is used subject to the following conditions:
• Super may only be used within a subclass constructor method.
• The call to superclass constructor must appear as the first statement within the subclass
constructor.
• The parameters in the super call must match the order and type of the instance variable
declared in the superclass.
Multilevel Inheritance:
The mechanism of deriving a class from another derived class is called as multilevel inheritance.
Syntax: class B extends A
{
Body of B class;
}
class C extends B
{
Body of C class;
}
// WAP to implement Multilevel Inheritance.
class Student
{
int rollno;
String name;
void get(int r, String n)
{
rollno = r;
name = n;
}
void put()
{
System.out.println("Roll Number : "+rollno);
System.out.println("Name : "+name);
}
}
class Sports extends Student
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 4
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
{
int sport_marks;
void accept(int s)
{
sport_marks = s;
}
void display()
{
System.out.println(“Sports Marks : “+sport_marks);
}
}
class Exam extends Sports
{
double percent;
void input(double p)
{
percent = p;
}
void output()
{
put();
display();
System.out.println("Percentage : "+percent);
}
}
class Inheritance3
{
public static void main(String args[])
{
Exam e = new Exam();
e.get(15,"Disha");
e.accept(6);
e.input(89.25);
e.output();
}
}
Output: Roll Number : 15
Name : Disha
Sport Marks : 6
Percentage: 89.25
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 5
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Hierarchical Inheritance:
The mechanism of deriving more than one derived classes from a single base class is called as
hierarchical inheritance.
Syntax: class B extends A
{
Body of B class;
}
class C extends A
{
Body of C class;
}
class D extends A
{
Body of D class;
}
// WAP to implement Hierarchical Inheritance.
class A
{
int x;
void get()
{
x=10;
}
}
class B extends A
{
int p;
void calculate()
{
p=15;
System.out.println("Result B = " + p*x);
}
}
class C extends A
{
int q;
void calculate()
{
q=25;
System.out.println("Result C = " + q*x);
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 6
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
}
}
class D extends A
{
int r;
void calculate()
{
r=35;
System.out.println("Result D = " + r*x);
}
}
class Inheritance4
{
public static void main(String args[])
{
B bobj = new B( );
C cobj = new C( );
D dobj = new D( );
bobj.calculate();
cobj.calculate();
dobj.calculate();
}
}
Output: Result B = 150
Result C = 250
Result D = 350
Use of super Keyword:
• We can use super keyword for two purpose as follows:
To call Super Class constructor from Derived Class:
• Sub Class constructor can call Super Class constructor as follows:
super(); or super(parameter_list);
• First form is used to call default constructor of super class where as second form is used to
call parameterized constructor of super class.
• If super class is having no-argument constructor then it is not necessary to use super keyword
in sub class constructor, in such case compiler automatically inserts a call to the no-argument
constructor of super class.
• If super class is having parameterized constructor then it is compulsory for derived class
constructor to have super keyword with proper parameters to call super class constructor,
otherwise compile-time error will generate.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 7
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
• Object is the highest level super class of Java, if subclass constructor invokes super class
constructor, either explicitly or implicitly there will be whole chain of constructors called. It
is called constructor chaining.
// Program to demonstrate use of super to call super class constructor.
class Student
{
int rollno;
String name;
Student(int r, String n)
{
rollno = r;
name = n;
}
void put()
{
System.out.println("Roll Number : "+rollno);
System.out.println("Name : "+name);
}
}
class Exam extends Student
{
double percent;
Exam(int r, String n, double p)
{
super(r, n);
percent = p;
}
void output()
{
put();
System.out.println("Percentage : "+percent);
}
}
class Inheritance2
{
public static void main(String args[])
{
Exam e = new Exam(15, “Disha”, 89.25);
e.output();
}
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 8
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Output: Roll Number: 15
Name: Disha
Percentage: 89.25
To Access SuperClass Members:
• We can access members of super class that has been hidden (overridden) by the members of
subclass. super.member;
Example:
class SuperClass
{
void show()
{
System.out.println(“Show of super class”);
}
}
classSubClass extends SuperClass
{
void show()
{
super.show(); // call show() of super class
System.out.println(“Show of sub class”);
}
public static void main(String args[])
{
SubClass s=new SubClass();
s.show(); // call show() of sub class
}
}
Output: Show of super class
Show of sub class
Co n s t r u c t o r E x e c u t i o n :
• In the class hierarchy, constructors are called in order of derivation, from super class to sub
class.
• Since super() must be the first statement executed in a subclass constructor, this order is same
weather super() is used or not.
• If super() is not used, then default or parameter less constructor of each super class will be
executed.
Example:
class A
{
A()
{
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 9
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
System.out.println(“Inside A’s Constructor”);
}
}
class B extends A
{
B()
{
System.out.println(“Inside B’s Constructor”);
}
}
class C extends B
{
C()
{
System.out.println(“Inside C’s Constructor”);
}
}
classConstExec
{
Public static void main(String args[])
{
C cobj = new C();
}
}
Output: Inside A’s Constructor
Inside B’s Constructor
Inside C’s Constructor
M e t h o d O v e r r i d i n g:
• When a method in a subclass has the same name and type signature as a method in its
superclass, then it is called as method overriding.
• When an overridden method is called from within a subclass, it will always refer to the
subclass method.The superclass method will be hidden.
• Which function to call is depending on type of object used? If we use base class object then
member function of base class get called, but if we use derived class object then member
function of derived class get called.
// Program to demonstrate method overriding.
class BC
{
void show()
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 10
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
{
System.out.println("Base Class Show");
}
};
class DC extends BC
{ void show()
{
System.out.println("Derived Class Show");
}
};
class MOverride
{
public static void main(String args[])
{
BC bobj=new BC();
DC dobj=new DC();
bobj.show(); // calls base class show()
dobj.show(); // calls derived class show()
}
}
Output: Base Class Show
Derived Class Show
D i f f e r e n c e b e t w e e n M e t h o d a n d Co n s t r u c t o r :
Function Overloading Function Overriding
Using same function name more than once in Using same function name and parameters in
a program, but with different parameters list is base class and derived class, with different
known as function overloading. function body is known as function
overriding.
It is called as static polymorphism or early It is called as dynamic polymorphism or late
binding. binding.
It is implemented at compile time since the It is implemented at run time since the
compiler knows which method to call compiler does not know the method to be
depending on number of parameters pass and executed, whether it is the base class method
their data types. that will be called or derived class method.
It is easy to achieve and fast. It is difficult to achieve and slow.
It is not related with inheritance. It is related with inheritance.
Ex: Give Example Ex: Give Example
Keyword “final”:
To declare constant / named constant:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 11
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
• A variable can be declared as final, so its value cannot be modified. We must initialize a final
variable when it is declared.
• We must write down final variable name as all uppercase letters.
• Variables declared as final do not occupy memory on a per-instance basis. Thus, a
finalvariable is a constant.
Example: final int PASSCRITERIA = 40;
finalfloatPI = 3.14f;
Use of final with Inheritance:
To prevent method overriding:
• To prevent a method from overriding,specify final as a modifier at the start of its declaration.
• Methods declared as final cannotbe overridden.
Example:
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!");
}
}
• Because meth( ) is declared as final, it cannot be overridden in B. If we try, a compile-time
error will result.
• Methods declared as final can provide a performance enhancement. Compiler is free to inline
call to them because they will not be overridden by a subclass. So it reduces overhead.
• Since final methods cannot be overridden, a callto it can be resolved at compile time. This is
called early binding.
Using final to Prevent Inheritance:
• Keyword final can be used to prevent a class from being inherited. To do this, precede the
• Declaring a class as final implicitly declares all of its methodsas final.
• It is illegal to declare a class as both abstract and final, as it is opposite concepts.
final class A
{
// ...
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 12
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
• It is illegal for B to inherit A since A is declared as final.
A b s t r a c t Cl a s s e s a n d M e t h o d s :
• Sometimes we want to define a superclass that declares the structure of a given abstraction
without providing a complete implementation of every method.
• That is, sometimes we want to create a superclass that only defines a generalized form that
will be shared by all of its subclasses, and each subclass will fill in the required details. Such
a class is called as Abstract Class.
• When class contains one or more abstract methods, it must be declared as abstract class.
• We cannot create objects of the abstract class.
• Syntax of abstract class: abstract class ClassName
{
// Body of abstract class
}
• By declaring methods as abstract it becomes compulsory for subclass to override that
method.
• If subclass does not override abstract method of superclass then subclass also becomes
abstract.
• These methods are sometimes referred to as subclasser responsibility because they have no
implementation specified in the superclass.
• We cannot declare abstract constructor or static methods.
• If any method of the class is abstract then that class must also be declared as abstract. If a
class contains an abstract method, the class must be abstract as well.
• Syntax of abstract method: abstract return_type method_name(parameter-list)
{
// Body of abstract method
}
// Abstract Method and Class.
abstract class Base
{
abstract void show();
}
class Derived extends Base
{
void show()
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 13
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
{
System.out.println("Derived class show");
}
}
class AbstractCls
{
public static void main(String args[])
{
Derived d = new Derived();
d.show();
}
}
Output: Derived class show
Static Members:
• A data member or member function of a class can be made static by using static keyword.
• Static variables are also known as class variables.
• Static member function can be called before creating any object of that class.
Characteristics:
1. It initializes to zero when the first object of class is created. Other initialization is not
permitted.
2. A static members can be accessed using the class name instead of its objects as:
class-name . variable;
class-name . function-name ();
3. Only one copy of static member is created for the entire class and is shared by all objects of
that class.
4. They are global in scope and its lifetime is the entire program.
5. Static variables are normally used to maintain values common to the entire class.
6. Static member function can have access to only other static members (functions & variables).
7. A static member function cannot refer to this or super in any way.
When to declare a member of a class static?
When we want to maintain values common to the entire class then we declare member of a class
as a static.
Example: class student
{
static int passcriteria;
int percentage;
};
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 14
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Here, passing criteria remains same for all students so it is declared as a static. But percentage
for every student may be different so percentage is non-static.
// Demonstrate static variables, methods, and blocks.
class MathOperation
{
static float mul(int a, int b)
{
System.out.println(“Multiplication = “ + a*b);
}
}
class MathApplication
{
public static void main(String args[])
{
MathOperation.mul(10,8); // called using class name
}
}
Output: Multiplication = 80
N e s t e d a n d I n n e r Cl a s s e s :
• It is possible to define a class within another class; such classes are known as nested classes.
• The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
defined within class A, then B is known to A, but not outside of A.
• A nested class has access to the members, including private members, of the class in which it
is nested. However, the enclosing class does not have access to the members of the nested
class.
• There are two types of nested classes:
o Static
o Non-static
• Static nested class is one which has the static modifier applied. Because it is static, it must
access the members of its enclosing class through an object. That is, it cannot refer to
members of its enclosing class directly. Because of this restriction, static nested classes are
seldom used.
• Inner class is a non-static nested class. It has access to all of the variables and methods of its
outer class directly in the same way that other non-static members of the outer class do. Thus,
an inner class is fully within the scope of its enclosing class
Example: class A
{
-------
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 15
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
class B
{
-------
}
-------
}
• Local inner class is declared within the body of a method.
• Anonymous inner class is declared within the body of a method without naming it.
Reason for using the nested classes:
o Logical grouping of the classes
o Increased encapsulation
o More readable, maintainable code
Dynamic Method Dispatch:
• Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time. It is use to achieve run-time polymorphism.
• In Java, a superclass reference variable can refer to a subclass object. Java uses this concept
to resolve calls to overridden methods at run time.
• When an overridden method is called using a superclass reference, Java determines which
version of the method to execute based upon type of the object referred at the time of the call.
• When different types of objects are referred, different versions of an overridden method will
be called. In other words, it is the type of the object being referred to (not the type of the
reference variable) that determines which version of anoverridden method will be executed.
// Dynamic Method Dispatch
class A
{
voidcallme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
voidcallme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
voidcallme()
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 16
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
{
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
}
}
Output: Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
Note: Overridden methods in Java are similar to virtual functions in C++.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 17
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Introduction and Defining Interface:
Q: What do you mean by multiple inheritance? How it is achieved in Java?
Q: What is an interface? What is its need? With program explain the use of interface.
Q: What is interface? Describe syntax, features and need of an interface.
Q: Why interface is needed in Java? Give example explaining its use.
Q: Explain with example how to achieve multiple inheritance with interface.
Q: Define interface. Give the general structure of interface.
Q: Define interface. How to create interface?
Multiple Inheritance:
• Single derived class with multiple base classes is called as multiple inheritance.
• Multiple inheritance allows us to join the features of number of existing classes.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 27
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
4. WAP to implement Area interface in Rectangle class.
Interface
interface Area
Area
{
implements
void compute(int l,int b);
} Class
Rectangle
class Rectangle implements Area
{
public void compute(int l,int b)
{
System.out.println("Rect Area = " + l*b);
}
}
class InterfaceDemo2
{
public static void main (String args[])
{
Rectangle r = new Rectangle();
r.compute(12,8);
}
}
Output: Rect Area = 96
5. WAP to implement “Multiple Inheritance”. Create two interfaces Account & Person.
Derive a class Customer and display all the information along with interest.
interface Account
Interface Interface
{ Account Person
void accept(int ano, int bal);
Implements
void display();
}
interface Person Class
{ Customer
void store(String nm, String ad);
void show();
}
class Customer implements Account, Person
{
int numyr, accno, balance;
float irate;
String name, addr;
Customer(float ir, int ny)
{
irate = ir;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 28
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
numyr = ny;
}
public void accept(int ano, int bal)
{
accno = ano;
balance=bal;
}
public void display()
{
System.out.println("Account Number: "+accno);
System.out.println("Balance: "+balance);
}
public void store(String nm, String ad)
{
name = nm;
addr = ad;
}
public void show()
{
System.out.println("Name: "+name);
System.out.println("Address: "+addr);
}
void intrest()
{
float simint = (balance * numyr * irate) / 100;
System.out.println("Simple Intrest: "+simint);
}
}
class InterfaceDemo
{
public static void main(String args[])
{
Customer c = new Customer(10.0,2);
c.accept(1234,1500);
c.store("Disha","Yavatmal");
c.display();
c.show();
c.intrest();
}
}
Output: Account Number: 1234
Balance: 1500
Name: Disha
Address: Yavatmal
Simple Intrest: 300.0
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 29
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
6. Program Exercise: WAP to implement following hierarchy.
Nesting of Interfaces:
• Interfaces can be nested similar to a class.
• An interface can be nested within:
o Another interface
o A class
• Nesting of interface is also called as interface within interface or interface within class or
inner interface. Enclosing interface or class is called as outer interface or outer class.
• Nesting of interface leads to the easy maintaining and accessing the group of related
interfaces.
• The nested interface cannot be accessed directly. To access nested interface, it must be
referred by the outer interface or class.
• Rules for nesting interface:
o Nested interface must be public if it is declared inside the interface.
o Nested interface can have any access modifier if it is declared inside the class.
o Nested interfaces are declared as static implicitly.
Nested Interface Inside Interface:
Syntax: interface InterfaceName
{
__________
__________
interface nested_interface_name
{
__________
__________
}
}
// Program to demonstrate interface inside interface.
interface Showable
{
interface Message
{
void msg();
}
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 30
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
class Test implements Showable.Message
{
public void msg()
{
System.out.println("This is Nested Interface Inside Interface");
}
}
class NestDemo1
{
public static void main(String args[])
{
Showable. Message m = new Test();
m.msg();
}
}
Output: This is Nested Interface Inside Interface
Nested Interface Inside Class:
Syntax: class ClassName
{
__________
__________
interface nested_interface_name
{
__________
__________
}
}
// Program to demonstrate interface inside interface.
class B
{
interface Message
{
void msg();
}
}
class Test implements B.Message
{
public void msg()
{
System.out.println("This is Nested Interface Inside Class");
}
}
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 31
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
class NestDemo2
{
public static void main(String args[])
{
B. Message m = new Test();
m.msg();
}
}
Output: This is Nested Interface Inside Class
Interface References:
• A reference variable can be declared as a class type or an interface type.
• If the variable is declared as an interface type, it can reference any object of any class that
implements the interface.
// Program to demonstrate interface reference variable.
interface Area Interface
Area
{
final static float PI=3.14f;
float compute (float x, float y); Implements
} Class Class
class Rectangle implements Area Rectangle Circle
{
public float compute (float x, float y)
{
return (x*y);
}
}
class Circle implements Area
{
public float compute (float x, float y)
{
return (PI*x*x);
}
}
class InterfaceTest
{
public static void main (String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area ar;
ar = rect;
System.out.println("Area of Rectangle = " + ar.compute(10,20));
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 32
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
ar=cir;
System.out.println("Area of Circle = " + ar.compute(10,0));
}
}
Output: Area of Rectangle = 200
Area of Circle = 314
S i m i l a r i t i e s b e t w e e n Cl a s s e s a n d I n t e r f a c e s :
Q: In what manner classes and interfaces are similar?
Q: What are similarities between class and interface?
Classes Interfaces
Classes can be extended to derive Interfaces can be extended to derive inheritance
inheritance. like classes.
Subclass can inherit all the members of SubInterface can inherit all the members of
superclass. The extends keyword is used. SuperInterface in same manner like subclasses.
The extends keyword is used.
Several classes can be combined together Several interfaces can be combined together into
into a single class. a single interface.
Classes are allowed to extend other Interfaces are allowed to extend other interfaces,
classes, and SubClasses inherit all the and SubInterfaces inherit all the methods of
methods of super classes. Super classes are SuperInterfaces. SuperInterfaces are still
still classes. Interfaces not classes.
Classes can be nested. Interfaces can also be nested.
D i f f e r e n c e s b e t w e e n Cl a s s e s a n d I n t e r f a c e s :
Q: How classes differ from interfaces?
Q: Distinguish Between class and interface.
Classes Interfaces
Starts with keyword class. Starts with keyword interface.
Classes contains zero, one or more abstract Interfaces contain all abstract methods by
methods. default.
Classes can contain method definition Interfaces cannot contain method definition
(body). (body).
Classes may or may not contain static and All constants in interfaces are static and final by
final variables or constants. default.
All Java programs contain classes as it is It’s not necessary for all Java programs to have
OOP language. interfaces.
Multiple inheritance is not possible with Multiple inheritance is possible with interfaces.
classes only.
A class can extend interfaces. An interface cannot extend classes.
Classes cannot be implemented. Interfaces can be implemented.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 33
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Syntax: Syntax:
class ClassName interface InterfaceName
{ {
variables declarations; static final variables declarations;
method with body; abstract method declarations;
} }
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 34
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
P a c k a g e s – P u t t i n g Cl a s s e s T o g e t h e r :
Q: Define package.
Q: What is package? Why packages are needed?
Concept:
• Reusability can be achieved using:
o Inheritance: By extending the classes.
o Interfaces : By implementing the interfaces.
• But this is limited to reusing classes within a program.
• If we want to use the classes from other programs without actually copying them into
program then this can be achieved in Java by using packages.
• The concept of package is very similar to class libraries in other languages.
• So, packages are another way of achieving reusability in Java.
Definition:
• Packages are the collection of functionally related:
o Classes
o interfaces
• Packages act as “containers” for classes.
Benefits / Advantages / Need of Package:
• The classes contained in the packages can be easily reused in any program.
• In packages, class name can be unique. That is, two classes in two different packages can
have the same name.
• Packages provide a way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
• Packages provide a way for separating designing from coding.
• Packages provide the reusability beyond the programs.
• With the package we can reuse the classes and interfaces, so it will reduce size and time.
Ty p e s o f P a c k a g e s :
Q: List any four built in packages from Java API along with their use.
Q: State any four system packages along with their use.
API
Packages
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 35
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Package Description
java.lang It include language support classes. These are the classes that Java compiler
itself uses and therefore they are automatically imported. It include classes for
Primitive Data Types Integer, Float and String, Math, Thread, Exception, etc.
java.util It include language utility classes such as Vector, Date, Scanner, etc.
java.io It include input / output related classes such as InputStreamReader,
DataInputStream, BufferedReader, IOException, stc.
java.awt It include classes for implementing GUI . It has Window, Font, Color, Button,
Menu, Checkbox, etc, classes.
java.net It include classes for networking and communication between client and server.
It has Socket, ServerSocket, InetAddress, etc. classes.
java.applet It includes classes for creating and implementing Applets such as Applet.
N a m i n g Co n v e n t i o n s :
• double y = java . lang . Math . sqrt(x);
Here, lang is package, Math is class and sqrt () is method.
• Packages in Java can be named using standard Java naming rules listed below:
1. Packages begin with lowercase letters, so that it can be distinguished from class name.
2. All class names begin with an uppercase letters.
3. Method names begin with lowercase letters, but if it contains more than one word then
subsequent word’s first letter must be uppercase.
4. Every package name must be unique. Duplicate names will cause run time error. Java is
best for Internet; many users work on Internet, so chances of using duplicate names are
high. To avoid this , we can use domain names as prefix to preferred package names.
Example: cbe .psg. mypackage
Here, cbe is city name and psg denotes organization name.
5. It is possible to create a hierarchy (nested) of packages within packages by separating
levels with dots.
Cr e a t i n g P a c k a g e s :
Q: How to create a package?
Q: Explain how user defined packages are created and accessed in Java.
Q: How to create package? Explain with suitable example.
Q: Write stepwise procedure to create user defined package.
Q: What is package? Why package are needed? How to add class to a package?
Q: How will you create package?
Steps for creating the package:
1. Declare the package at the beginning of a source file using the form:
Syntax: package packagename;
Example: package p1;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 36
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
2. Define the class that is to be put in the package and declare it public.
public class ClassName
{
// Class body
}
3. Create a subdirectory under the directory where the main source files are stored. Name of the
subdirectory must match with the name of package to be created i.e. p1.
4. Store the listing as the ClassName.java file in the subdirectory created p1.
5. Compile the file. This creates ClassName.class file in the subdirectory p1.
Note:
• Java supports package hierarchy. This is done by specifying multiple names in a package
statement separated by dots.
package firstpackage. secondpackage;
• This approach allows us to group related classes into a package and then group related
packages into a larger package.
• A Java package file can have more than one class. In such cases, only one of the classes may
be declared public and that class name with .java extension is the source file name.
• In above case java creates independent .class files for those classes.
A c c e s s i n g P a c k a ge s / I m p o r t i n g P a c k a g e s :
Q: Explain how user defined packages are created and accessed in Java.
Q: How will you access package?
Classes stored in packages can be accessed in two ways:
1. Fully qualified class name:
In this we use package name and then appending the class name to it using the dot operator.
Example: If we want to refer to the class Color in the awt package:
java.awt .Color;
This approach is suitable when we need to access the class only once or when we need not
have to access any other classes of the package.
Advantages:
• This approach is suitable when we need to access the class only once or when we need
not have to access any other classes of the package.
• In this approach we came to know that from where the particular class came from.
Disadvantages:
• This approach is not suitable if we want to use particular class many times or we want to
use many classes from that particular package.
• This approach is also not suitable if class or package name is too long to write.
2. Import statement:
This approach is suitable when we want to use a class in number of places in the program or
we may need many of the classes contained in a package. This approach is also suitable if the
class name or package name is too long to write.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 37
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Example: import packagename [ . subpackage1] [ . subpackage2] . ClassName;
or
import packagename . *;
First statement imports only specified class in the given package hierarchy.
Example: import java . awt . Color;
Second (shortcut) statement imports all the classes in the package. * denotes all.
Example: import java . awt . *;
Drawback of using shortcut approach is that we don’t come to know that from where
particular class came from.
Advantage:
• This approach is suitable if we want to use particular class many times or we want to use
many classes from that particular package.
Disadvantage:
• In it approach if we use * we don’t came to know from where particular class came from.
A c c e s s S p e c i f i e r s / Vi s i b i l i t y M o d e s :
Q: Write the effect of access specifiers’ public, private and protected in package.
Private: Anything that is declared as private can be used within a class only.
Friendly (default): Anything that is declared as friendly can be access within a package only.
Protected: Anything that is declared as protected can be access in all classes of same package
and sub classes in other packages.
Public: Anything that is declared as public can be access everywhere. If we declare anything as
a public in a package it means that can be used in same package and outside of the package.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 38
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
Using Packages:
• Consider following simple program with name ClassA.java:
package package1;
public class ClassA
{
public void displayA()
{
System.out.println(“Class A”);
}
}
• Importing the above package1 in program PackageTest1.java:
import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA();
objectA.displayA();
}
}
Output: ClassA
• Now, Consider following simple program with name ClassB.java:
package package2;
public class ClassB
{
protected int m = 10;
public void displayB()
{
System.out.println(“Class B”);
System.out.println(“m = “ + m);
}
}
• Importing the above package1 and package 2 in program PackageTest2.java:
import package1.ClassA;
import package2.*;
class PackageTest2
{
public static void main(String args[])
{
ClassA objectA = new ClassA();
ClassB objectB = new ClassB();
objectA.displayA();
objectB.displayB();
}
}
Output: ClassA
ClassB
m = 10
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 39
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
• When we import multiple packages it is likely that two or more packages contain classes with
identical names as follows:
package pack1;
public class Teacher
{ --------------- }
public class Student
{ --------------- }
package pack2;
public class Courses
{ --------------- }
public class Student
{ --------------- }
• Above packages can be imported like follows:
import pack1.*;
import pack2.*;
Student stud1; // invalid, Student class contains in both packages
pack1.Student stud1; // valid
pack2.Student stud2; // valid
Teacher tech1; // valid
Courses cors1; // valid
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 40
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
A d d i n g a Cl a s s i n ( Ex i s t i n g) P a c k a ge :
Q: How to add a class in existing package? Explain.
• It is possible to add a class to an existing package. Consider existing packages as follows:
package p1;
public ClassA
{
// Body of ClassA
}
• Above package has already one public class named ClassA. Now we want to add another
public class ClassB to this existing package p1.
• Steps for Adding a Class in (Existing):
1. Define the ClassB as public as follows, the file should have package p1; statement at top:
package p1;
public ClassB
{
// Body of ClassB
}
2. Store the program as the ClassB.java file in the subdirectory named p1.
3. Compile the ClassB.java file. This creates ClassB.class file in the subdirectory p1.
Cr e a t i n g P a c k a g e w i t h M u l t i p l e P u b l i c C l a s s e s :
Q: How to create package with multiple public classes? Explain.
• Since a Java source file can have only one class declared as public, we cannot put two or more
public classes together in a file in package program.
• The above restriction is because of that the file name should be same as the name of the public
class with .java extension.
• Steps to create a package with multiple public classes is as follows:
1. Declare the package at the beginning of a source file using the form:
Syntax: package packagename;
Example: package p1;
2. Create a subdirectory under the directory where the main source files are stored. Name of
the subdirectory must match with the name of package to be created i.e. p1.
3. Define first class that is to be put in the package and declare it public.
package p1;
public class ClassA
{
// Body of ClassA
}
4. Store the above program as the ClassA.java file in the subdirectory created i.e. p1.
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 41
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
5. Define second class in separate file that is to be put in the existing package p1 and declare
it public.
package p1;
public class ClassB
{
// Class body
}
6. Store the above program as the ClassB.java file in the subdirectory created i.e. p1.
7. Compile both the files separately. This creates two .class file in the subdirectory p1.
Cr e a t i n g P a c k a g e a n d S u b P a c k a ge s ( M u l t i l e v e l H i e r a r c h y ) :
Q: Describe how to create a multilevel hierarchy with an example.
Q: How to create and access sub packages in Java?
• Steps for creating the sub-package:
1. Declare the package at the beginning of a source file using the form:
Syntax: package packagename;
Example: package p1;
2. Create a subdirectory under the directory where the main source files are stored. Name of
the subdirectory must match with the name of package to be created i.e. p1.
3. Define first class that is to be put in the package and declare it public.
package p1;
public class ClassA
{
// Body of ClassA
}
4. Store the above program as the ClassA.java file in the subdirectory created i.e. p1.
5. Create a subdirectory under the directory p1 and name it p2.
6. Define second class in subdirectory p2 as follows:
package p1.p2;
public class ClassB
{
// Class body
}
7. Store the above program as the ClassB.java file in the subdirectory created i.e. p2.
8. Compile both the files separately. This creates ClassA.class file in the subdirectory p1
and ClassB.class file in the subdirectory p2.
• Steps for accessing the sub-package:
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 42
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
1. import the package as follows:
import p1.*;
import p1.p2*;
2. Use it as per requirement as follows:
import p1.*;
import p1.p2*;
class ClassName
{
public static void main(String args[])
{
// use classes from packages p1 and p2 as per requirement
}
}
H i d i n g Cl a s s e s :
• When we import package using * all public classes are imported.
• Sometimes we don’t want to allow import of certain classes from outside of the package.
This can be achieved by declaring those classes as non-public. It gives the idea of hiding the
classes.
• Example:
public p1;
public class X // public class available inside and outside of the package
{
// body of X
}
class Y // non-public class, hidden, available the inside package only
{
// body of Y
}
• Now, consider:
import p1.*;
X objectx; // valid
Y objecty; // invalid, class Y is not available outside
Static Import:
Q: Explain static import feature with example.
Q: What is the use of static import? Explain.
• This feature eliminates the need of qualifying a static member with the class name. So we can
import classes from packages statically and use them without qualifying the class name.
• Without static import feature, we had to use the static member with qualifying class name.
For example, double cirarea = Math.PI * rad * rad;
In above code, PI is the static member of the class Math. So it is used with class name Math.
• If we use static import, we can write above statement as: double cirarea = PI * rad * rad;
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 43
Mr. Atul Bondre (M.Sc. Computer Science) MN: 7020499143 MindSpace Computers Java-Unit-3
• This feature is also used to import the interface statically.
• Thus we can use static members without qualifying the class name or interface name.
• Also the static import feature reduces the redundancy of using the qualifying class name or
interface name while using static members.
• Syntax: import static package_name . subpackage_name . Classname.staticmember_name;
or
import static package_name . subpackage_name . ClassName . *;
// Program to demonstrate static import feature.
import static java.lang.Math.*;
class MathOp
{
void circle(double r)
{
double area = PI*r*r; // No need to use Math.PI
System.out.println(“Circle Area = “ + area);
}
public static void main(String args())
{
MathOp obj = new MathOp();
obj.circle(2.3);
}
}
Output: Circle Area = 16.619025
Space for Extra Work:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
© Copy Right To MindSpace Computers, Ytl (Not For Private Circulation) Page 44