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

Java Programming UNIT 2 Notes

The document discusses inheritance in Java, defining it as a mechanism where one class acquires properties from another, with subclasses inheriting from superclasses. It outlines types of inheritance such as single and multilevel inheritance, explains the use of the 'super' keyword, and details access specifiers (public, protected, private, and default) that control visibility of class members. Additionally, it touches on interfaces as blueprints for classes, emphasizing code reusability and the hierarchical structure of classes.

Uploaded by

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

Java Programming UNIT 2 Notes

The document discusses inheritance in Java, defining it as a mechanism where one class acquires properties from another, with subclasses inheriting from superclasses. It outlines types of inheritance such as single and multilevel inheritance, explains the use of the 'super' keyword, and details access specifiers (public, protected, private, and default) that control visibility of class members. Additionally, it touches on interfaces as blueprints for classes, emphasizing code reusability and the hierarchical structure of classes.

Uploaded by

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

JAVA PROGRAMMING

UNIT –II
INHERITANCE:
 Inheritance can be defined as the process where one object acquires the properties of
another.
 With the use of inheritance the information is made manageable in a hierarchical order.
 In the terminology of Java, a class that is inherited is called a super class.
 The class that does the inheriting is called a subclass. Therefore, a subclass is a
specialized version of a super class. It inherits all of the instance variables and methods
defined by the super class and add its own, unique elements.
 The most commonly used keyword would be extends and implements. These words
would determine whether one object IS-A type of another. By using these keywords we
can make one object acquire the properties of another object.
 The general form of a class declaration that inherits a super class is shown here:
class subclass-name extends super class-name {
// body of class
}
 The following kinds of inheritance are there in java.
 Single Inheritance
 Multilevel Inheritance (Inheritance Hierarchy)
 Java does not support multiple Inheritance
 Multiple Inheritance: The mechanism of inheriting the features of more than one base
class into a single class is known as multiple inheritance.
 The multiple inheritance can be achieved by using the interface.
 In Java Multiple Inheritance can be achieved through use of Interfaces by implementing
more than one interfaces in a class.

SINGLE INHERITANCE:
 When a subclass is derived simply from it's parent class then this mechanism is known as
simple inheritance.
 In case of simple inheritance there is only a sub class and it's parent class. It is also called
as one level inheritance.
 Eg:
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A { // Create a subclass by extending class A.
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
subOb.i = 7; // subclass has access to all public members of its superclass
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Note:
A class member that has been declared as private will remain private to its class. It is not
accessible by any code outside its class, including subclasses.
Eg 2:
class Box {
double width, height ,depth;
Box(Box ob) { // construct clone of an object & pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight; // weight of box
BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
} }
 Once a super class is created that defines the general aspects of an object , that super class
can be inherited to form specialized classes.
 Each sub class simply adds its own, unique attributes. i.e) inheritance provides reusability
of code.

Multilevel Inheritance:

 When a subclass is derived from a derived class then this mechanism is known as the
multilevel inheritance. The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above ( parent ) class.
 Eg:
class student
{
int roll;
void get(int a)
{
roll =a;
System.out.println(roll);
}
}
class test extends student
{ int m1,m2,m3;

void getmarks(int a,int b,int c)


{
m1=a;m2=b;m3=c;
System.out.println(m1+""+m2+""+m3);
}
}
class result extends test
{ int tot;
void display()
{
tot=m1+m2+m3;
System.out.println(tot);
}
}
class Inherit
{ public static void main(String args[])
{ result a1= new result();
a1.get(1);
a1.getmarks(75,80,78);
a1.display();
} }

A Superclass Variable Can Reference a Subclass Object:


 A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass.
 Eg:
class RefDemo {
public static void main(String args[]) {
BoxWeight wb = new BoxWeight(3, 5, 7, 8.37);
Box b = new Box();
double vol;
vol = wb.volume();
System.out.println("Volume of weightbox is " + vol);
System.out.println("Weight of weightbox is " +wb.weight);
b = wb;
vol = b.volume(); // OK, volume() defined in Box
System.out.println("Volume of plainbox is " + vol);
/* The following statement is invalid because plainbox
does not define a weight member. */
// System.out.println("Weight of plainbox is " +b.weight);
}
}

super keyword:
 The super is java keyword. As the name suggest super is used to access the members of
the super class. It is used for two purposes in java.
 The first use of keyword super is to access the hidden data variables of the super class
hidden by the sub class.
 E.g. Suppose class A is the super class that has two instance variables as int a and float b.
class B is the subclass that also contains its own data members named a and b. then we
can access the super class (class A) variables a and b inside the subclass class B just by
calling the following command.
 super.member;
 Here member can either be an instance variable or a method. This form of super most
useful to handle situations where the local members of a subclass hides the members of a
super class having the same name. The following example clarify all the confusions.
 class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
public static void main(String[] args){
B subobj = new B(1, 5);
subobj.Show();
}
}
 Output:
 C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Ex 2:
class A {
int i;
}
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2

Use of super to call super class constructor:


 The second use of the keyword super in java is to call super class constructor in the
subclass. This functionality can be achieved just by using the following command.
 super(param-list);
 Here parameter list is the list of the parameter requires by the constructor in the super
class. super must be the first statement executed inside a super class constructor. If we
want to call the default constructor then we pass the empty parameter list. The following
program illustrates the use of the super keyword to call a super class constructor.
 Eg:
class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
 Eg2:
class A{
int a, b,c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}

public static void main(String args[]){


B b = new B(4,3,8,7);
b.Show();
}
}
 Output:
 C:\>java B
a = 4
b = 3
c = 8
d=7
When Constructors Are Called:
 When a class hierarchy is created, constructors are called in order of derivation, from
superclass to subclass.
 Further, since super( ) must be the first statement executed in a subclass' constructor,this
order is the same whether or not super( ) is used.
 If super( ) is not used, then the default or parameterless constructor of each superclass
will be executed.
 Eg: class A {
A() {
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.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A's constructor
Inside B's constructor
Inside C's constructor

INHERITANCE HIERARCHY OR CLASS HIERARCHY:


 Inheritance need not stop at deriving one layer of classes.
 The collection of all classes extending from a common superclass is called an inheritance
hierarchy.
 The path from a particular class to its ancestors in the inheritance hierarchy is its
inheritance chain.
 Eg:
Employee

Manager Secretary Programmer

Executive

 Eg: multi level inheritance program.
 Here Employee is the super class . Manager, Secretary and Programmer are the sub
classes of Employee class. Executive is a sub class of Manager class
 Eg 2: Inheritance hierarchy for the frame and component classes in AWT

object

component

container

window
Jcomponent

frame

jpanel
jframe

Access Specifiers:

 Access specifiers allows the programmer to control the visibility of class members.

 Java allows you to control access to classes, methods, and fields via access specifiers.

 Java supplies a rich set of acess specifiers.some aspects of access control are related mostly to
inheritance or packages(grouping of classes)

 Java’s access specifiers are:

- Private

- Public

- Protected
- Default

Public:

 Public classes, methods, and fields can be accessed from everywhere.

 The only constraint is that a file with Java source code can only contain one public class whose
name must also match with the filename. If it exists, this public class represents the application
or the applet, in which case the public keyword is necessary to enable the Web browser or
appletviewer to show the applet.

 Eg:

public class Square { // public class

public x, y, size; // public instance variables

public void mtd()

// code

Protected:

 Protected methods and fields can only be accessed within the same class to which the methods
and fields belong, within its subclasses, and within classes of the same package, but not from
anywhere else.

 The protected access level is used when it is appropriate for a class's subclasses to have access
to the method or field, but not for unrelated classes.

Default (no specifier):

 If you do not set access to specific level, then such a class, method, or field will be accessible
from inside the same package to which the class, method, or field belongs, but not from outside
this package. This access-level is convenient if you are creating packages.

Private:

 Private methods and fields can only be accessed within the same class to which the methods
and fields belong.
 Private methods and fields are not visible within subclasses and are not inherited by subclasses.
So, the private access specifier is opposite to the public access specifier.

 It is mostly used for encapsulation: data are hidden within the class and accessor methods are
provided.

 An example, in which the position of the upper-left corner of a square can be set or obtained by
accessor methods, but individual coordinates are not accessible to the user.

public class Square { // public class

private double x, y // private (encapsulated) instance variables

public setCorner(int x, int y) { // setting values of private fields

this.x = x;

this.y = y;

public getCorner() { // setting values of private fields

return Point(x, y);

 Summary of Access Specifiers:

Specifier class subclass package world

Private Y

protected Y Y Y
public Y Y Y Y

(none)default Y Y

Situation public protected default private

Accessible to class
yes yes yes no
from same package?

Accessible to class yes no, unless it is a subclass no no


from different package?

Note:

 The difference between the default access which is in fact more restricted than the protected
access. Without access specifier (the default choice), methods and variables are accessible only
within the class that defines them and within classes that are part of the same package. They
are not visible to subclasses unless these are in the same package. protected methods and
variables are visible to subclasses regardless of which package they are in.

INTERFACE:

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.

Why use Java interface?

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public, static
and final by default. A class that implements an interface must implement all the methods
declared in the interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
Internal addition by the compiler

In other words, Interface fields are public, static and final by default, and the methods are public
and abstract.

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Output:

Hello

Java Interface Example: Drawable


In this example, the Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its
implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawab
le()
16. d.draw();
17. }}

Java Interface Example: Bank


Let's see another example of java interface which provides the implementation of Bank interface.

File: TestInterface2.java

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}

POLYMORPHISM:
 Refers to an object’s ability to behave differently depending on its type
 Poly = ‘many’
 morph = ‘form’
 An operation may exhibit different behaviors in different instances.
 Example: +operator will produce a sum when the operands are numerals and a third
string when the operands are strings.
 1+2=3
 ‘Kc’+’tech’=’kctech’
 Making an operator to exhibit different behavior is referred as operator overloading
 Two types of polymorphism:
 Static Polymorphism
Eg: Overloading
 Run Time Polymorphism
Eg: overriding and dynamic method binding
Method Overloading:
 Practice of using same method name to denote several different operations
 Overloaded methods are methods with the same name signature but either a different
number of parameters or different types in the parameter list.
 Method overloading is a static polymorphism.
 For example, consider a class String which is designed to simplify string operations
 Append functions are overloaded to accept different types of data
 One Append function appends an integer value to string, another Append function
appends a float value
 void Append(int)
 void Append(float)
 The appropriate function will be invoked based on the type of the argument used in the
function call
 Any number of functions can have the same name as long as they differ in any one of the
following
 Type of arguments
 Number of arguments
 Eg Program : [ refer unit I notes]
Method overriding:
 Redefining a base class method in a sub class is called method overriding
 They have the same signature and the subclass definition is used.
 In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass.
 When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass.
 The version of the method defined by the superclass will be hidden.
 An overriding method can call an overridden method using the syntax
super.methodName()
 Note: static methods cannot be over riden
 Eg:
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
Eg 2:
class A {
int i;
A(int a, int b) {
i = a+b;
}
void add() {
System.out.println("Sum of a and 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 and c is: " + j);
}
}
class MethodOverriding {
public static void main(String args[]) {
B b = new B(10, 20, 30);
b.add();
}
}
Output:
Overloading Overriding

Signature has to be different. Just a difference Signature has to be the same. (including the
in return type is not enough return type)
Accessibility may vary freely. Overriding methods cannot be more private
than the overridden methods.

Exception list may vary freely. Overriding methods may not throw more
checked exceptions than the overridden
methods.
Just the name is reused. Methods are Related directly to sub-classing. Overrides the
independent methods. Resolved at compile- parent class method. Resolved at run-time
time based on method signature. based on type of the object.

Can call each other by providing appropriate Overriding method can call overridden method
argument list. by super.methodName(), this can be used only
to access the immediate super-class's method.
super.super won't work. Also, a class outside
the inheritance hierarchy can't use this
technique.
Methods can be static or non-static. Since the static methods don't participate in overriding,
methods are independent, it doesn't matter. But since they are resolved at compile time based
if two methods have the same signature, on the type of reference variable. A static
declaring one as static and another as non- method in a sub-class can't use 'super' (for the
static does not provide a valid overload. It's a same reason that it can't use 'this' for)
compile time error.
Remember that a static method can't be
overridden to be non-static and a non-static
method can't be overridden to be static. In
other words, a static method and a non-static
method cannot have the same name and
signature (if signatures are different, it would
have formed a valid overload)
There's no limit on number of overloaded Each parent class method may be overridden at
methods a class can have. most once in any sub-class. (That is, you
cannot have two identical methods in the same
class)
Final Keyword:
1. To declare a constant:
Eg: final int a=5;
2. To prevent inheritance
Eg: final class sup
{
// body
}
Class sub extends sup // not possible
{ }
A class declared as final can’t be inherited by other classes.
Declaring a class as final implicitly declares all of its methods as final, too.

3. To prevent Method over riding:


 Methods declared as final cannot be overridden.
Eg:
class sup
{
Final void func1()
{
// body
}
}
Class sub extends sup
{
void func1() // not possible
{
// body
}
}
A method declared as final can’t be over ridden by the sub classes.
Eg : 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!");
} }

Abstract Classes:

 There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method.
 That is, sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to fill in the
details.
 Such a class determines the nature of the methods that the subclasses must implement.

 A super class that only defines a generalized form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details is called an abstract class.
 An abstract class just specifies what to do and not how to do it
abstract method:
 Certain methods be overridden by subclasses by specifying the abstract type modifier.
 These methods are sometimes referred to as subclasser responsibility because they have
no implementation specified in the superclass.
 Thus, a subclass must override them—it cannot simply use the version defined in the
superclass.
 To declare an abstract method, use this general form:
 abstract type name(parameter-list);
 No method body is present.
 Any class that contains one or more abstract methods must also be declared abstract.
 To declare a class abstract,
 simply use the abstract keyword in front of the class keyword at the beginning of
the class declaration.
 Eg : abstract class sample
{
// body
}
 There can be no objects of an abstract class.
 That is, an abstract class cannot be directly instantiated with the new operator.
 Such objects would be useless, because an abstract class is not fully defined.
 Also, you cannot declare abstract constructors, or abstract static methods.
 Any subclass of an abstract class must either implement all of the abstract methods in the
superclass, or be itself declared abstract.
 Example:
abstract class A
{
abstract void callme();
void callmetoo() { // concrete methods are still allowed in abstract classes
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
 Although abstract classes cannot be used to instantiate objects, they can be used to create
object references, because Java's approach to run-time polymorphism is implemented
through the use of superclass references. Thus, it must be possible to create a reference to
an abstract class so that it can be used to point to a subclass object.
 Eg:
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

PACKAGES:
 two of Java's most innovative features: packages and interfaces
 In general, a Java source file can contain any (or all) of the following four internal parts:
 A single package statement (optional)
 Any number of import statements (optional)
 A single public class declaration (required)
 Any number of classes private to the package (optional)
 A package is a collection of related classes and interfaces in Java
 Packages are containers for classes that are used to keep the class name space
compartmentalized.
 Packages help in logical grouping of classes and interfaces
 All the classes and interfaces that are used for performing I/O operations can be
placed in the same package
 All the classes and interfaces that are used for writing network programs can be
placed in the same package
 Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions.
 Java provides a mechanism for partitioning the class name space into more manageable
chunks. This mechanism is the package.
 The package is both a naming and a visibility control mechanism.
 We can define classes inside a package that are not accessible by code outside that
package.
 Class members can also be defined that are only exposed to other members of the same
package.
 Packages allow the classes to have intimate knowledge of each other, but not expose that
knowledge to the rest of the world.

PACKAGES TO PREVENT NAME CLASH


 Packages prevent the clash of class/interface names
 More than one class/interface can have the same name
 They should be in two different packages
 The fully qualified names of these classes/interfaces will be different

CREATING A PACKAGE
 Simply include a package command as the first statement in a Java source file.
 Any classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored.
 Eg:
 Create a folder pack
 Place the following program in this folder
 Syntax for defining a package:
 Package <package name>
 Eg: package pack;
 Java uses file system directories to store packages.
 More than one file can include the same package statement.
 The package statement simply specifies to which package the classes defined in a file
belong.
 To create a hierarchy of packages. The general form of a multileveled package statement
is shown here:
 package pkg1[.pkg2[.pkg3]];
 Eg: java.awt.image;

Program to Implement a stack


package pack;
public class Stack {
int stck[] = new int[10];
int tos;
public Stack() {
tos = -1; // Initialize top-of-stack
}
public void push(int item) { // Push an item onto the stack
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
public int pop() { // Pop an item from the stack
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}

IMPORTING A CLASS
 It is difficult to use the fully qualified name of a class through out the program
 The import statement can be used to import a class into a program so that the class name
need not be fully qualified
 Syntax: import <package name>.<class name>;
 Eg: import pack.stack;
/*Spackage.java*/
import pack.Stack;
class StackPackage
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
for(int i=0; i<10; i++)
mystack1.push(i); // push some numbers onto the stack
System.out.println("Stack in mystack1:"); // pop those numbers off the stack
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
}
}

IMPORTING ALL CLASSES AND INTERFACES


 The statement import pack.*
 Imports all the classes and interfaces in the specified package
 All the classes and interfaces in this package can be used without qualifying them
with package name
BEST PRACTICE: Import only those classes that are required in your code, do not import
the entire package
PACKAGES AND CLASSPATH
 By default, java run-time system uses the current working directory as its starting point
and if the package is in the current directory/sub directory it will be found.
 Compiler and JVM must know location of the packages
 An environment variable classpath needs to be set
 The classpath will be pointing to a folder be one level up the package folder
 If the folder hierarchy is C:\program files\java\jdk 1.6.0\bin\pack, the classpath
should be set using the following statement

>set classpath = %classpath%; program files\java\jdk 1.6.0\bin\pack


SUB PCKAGES:
 A package can in turn contain another sub package
 To create a sub package policy in insurance
 Create a sub folder policy inside the folder insurance
 Place the following code in the folder policy and compile

ACCESS MODIFIERS - REVISITED


 Java has 4 access control modifiers
 private: Accessible only within the class
 default: No keyword, Accessible only within the package
 protected: Similar to default with the addition that available to all child classes;
that is, even if child class is in a different package
 public: Accessible to all
 Data Members and Methods can have any of these specifier
 Classes and Interfaces can have either the public access or the default access
 Classes and packages are both means of encapsulating and containing the name space and
scope of variables and methods.
 Packages act as containers for classes and other subordinate packages.
 Classes act as containers for data and code.
 The class is Java's smallest unit of abstraction.
 Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:
 Subclasses in the same package
 Non-subclasses in the same package
 Subclasses in different packages
 Classes that are neither in the same package nor subclasses
 Class Member Access
Private N o modifier Protected Public
Same class Yes Yes Yes Yes
Same package-subclass No Yes Yes Yes
Same package non subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non subclass No No No Yes

USES OF PACKAGES
 Logical grouping of classes and interfaces
 Avoiding clash of names
 Provides an extra level of protection to its members
 Classes can be reused easily
STANDARD JAVA PACKAGES
 java.lang
 Contains classes that form the basis of the design of the Java programming
language
 No need to explicitly import this package
 The String class, System class etc, belong to this package
 java.io
 Classes and interfaces to perform I/O operations
 java.util
 Utility classes and interfaces like List, Calendar etc
 java.awt
 Classes and interfaces to create GUI

You might also like