Java Basic

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 189

JAVA BASIC

LECTURER
DEPARTMENT OF CSE
A LOOK PROCEDURE-ORIENTED
PROGRAMMING
High level languages such as COBOL,FORTRAN and C
Characteristics
 Emphasis is on doing things(algorithems)
 Large programs are divided into smaller programs
known as functions.
 Most of the function share global data
 Data move openly around the system from function to
function
 Functions transforms data from one form to another
 Employs top-down approach in program design
OBJECT-ORIENTED PROGRAMMING
PARADIGM
Some of the striking features of object-oriented programming are:
 Emphasis is on data rather than procedure
 Programs are divided in to what are known as objects
 Data structures are designed such that they characterize the
objects
 Functions that operate on the data of an object are tied together in
the data structure
 Data is hidden and cannot be accessed by external functions
 Objects may communicate with each other through functions
 New data and functions can be easily added whenever necessary
 Follows bottom-up approach in program design
PROGRAMMING

Objects
Classes
Data Abstraction
Data Encapsulations
Inheritance
Polymorphism
Dynamic buinding
Message passing
Java - An Introduction
Java - The new programming language
developed by Sun Microsystems in 1991.
Originally called Oak by James Gosling, one of
the inventors of the Java Language.
Originally created for consumer electronics
(TV, VCR, Freeze, Washing Machine, Mobile
Phone).
Features of JAVA
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
Java is Compiled and Interpreted

Hardware and
Programmer
Operating System

Source Code Byte Code


Text Editor Compiler Interpreter
.java file .class file
Notepad, javac java
emacs,vi appletviewer
netscape
Total Platform Independence

JAVA COMPILER
(translator)

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Macintosh Solaris Windows NT


Rich Class Environment
Core Classes
language
Utilities
Input/Output
Low-Level Networking
Abstract Graphical User
Interface
Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs
Overlap of C, C++, and Java

C++

C Java
Java better than C++ ?
No Typedefs, Defines, or Preprocessor
No Global Variables
No Goto statements
No Pointers
No Unsafe Structures
No Multiple Inheritance
No Operator Overloading
Java Applications
We can develop two types of Java programs:
Stand-alone applications
Web applications (applets)
Applications v/s Applets
Different ways to run a Java executable
are:
Application- A stand-alone program that can be invoked from
command line . A program that has a “main”
main method

Applet- A program embedded in a web page , to be run when the


page is browsed . A program that contains no “main” method
Applets v/s Applications
Different ways to run a Java executable
are
Application- A stand-alone program that can be invoked from
command line . A program that has a “main”
main method
Applet- A program embedded in a web page , to be run when the
page is browsed . A program that contains no “main” method
Application –Executed by the Java
interpreter.
Applet- Java enabled web browser.
Java Development Kit
JDK is used to create and run the java
program
javac - The Java Compiler
java - The Java Interpreter
Jdb - The Java Debugger
appletviewer -Tool to run the applets
javap - to print the Java bytecodes
javaprof - Java profiler
javadoc - documentation generator
javah - creates C header files
Process of Building and Running Java Programs

Text Editor

Java Source
javadoc HTML Files
Code

javac

Java Class File javah Header Files

java jdb

Outout
Java Program Structure

Documentation Section

Package Statement

Import Statements

Interface Statements

Class Declarations

Main Method Class


{
}
Hello World

// HelloWorld.java: Hello World program


import java.lang.*;
class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
Closer Look at - Hello World
import java.lang.*;
Java allows grouping of related classes into a package.
It allows different companies can develop different packages,
may even have same class and method names, but they differ
by package name:
ibm.mathlib.*
microsoft.mathlib.*
Helps in managing name clash problems.
Think of this package as library.
“import” statement somewhat serves similar purpose as C’s
#include
If you don’t add import statement, then you need utilise fully
qualified name.
ibm.mathlib.sin()
If you do “import ibm.*” then you can use mathlib.sin()
instead.
Java imports java.lang.* by default
So, You don't need to import java.lang.*
That means, you can invoke services of java’s
“lang” package classes/entities, you don’t need
to use fully qualified names.
We used System.out.println() instead of
java.lang. System.out.println()
public static void main(String args[])
public: The keyword “public” is an access specifier
that declares the main method as unprotected.
static: It says this method belongs to the entire class
and NOT a part of any objects of class. The main must
always be declared static since the interpreter users
this before any objects are created.
void: The type modifier that states that main does not
return any value.
More Java: Classes and static methods
// SquareRoot.java: compute square root of number

import java.lang.Math;

class SquareRoot
{
public static void main(String args [])
{
double x = 4;
double y;
y = Math.sqrt(x);
System.out.println("y= "+y);
}
}
Basic Data Types
Types
boolean either true or false
char 16 bit Unicode 1.1
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (singed)
float 32-bit floating point (IEEE 754-1985)
double 64-bit floating point (IEEE 754-1985)
String (class for manipulating strings)
Java uses Unicode to represent characters
internally
Variables

Local Variables are declared within the block of code

Variable has a type preceding the name

Initial value is set by initialization expressions.

type variableName = initialValue;

e.g. int x = 1;
Variables can be defined just before their usage (unlike C)
e.g., for( int i = 0; i < 10; i++)
Constants

Constants are similar to variables except that they


hold a fixed value. They are also called “READ”
only variables.

Constants are declared with the reserved


word “final”.
final int MAX_LENGTH = 420;
final double PI = 3.1428;

By convention upper case letters are used for


defining constants.
Declaring Constants - example
class CircleArea
{
public static void main(String args[])
{
final double PI = 3.1428;
double radius = 5.5; // in cms
double area;

area = PI * radius * radius;

System.out.println("Circle Radius = "+radius+" Area="+area);


}
}
Comments

English text scattered through the code are


comments
JAVA supports 3 types of comments
/* */ - Usually used from multi-line comments
// - Used for single line comments
/** */ - Documentation comments
Control Flow

Control Flow Statements in JAVA


while loop
for loop
do-while loop
if-else statement
switch statement
JAVA does not support a goto statement
Control Flow - Examples
while loop

while (squared <= MAX)


{
squared = lo * lo; // Calculate square
System.out.println(squared);
lo = lo + 1; /* Compute the new lo value */
}
Control Flow - Examples
for loop

for (int i = 1; i < MAX; i++)


{
System.out.println(i); // prints 1 2 3 4 5 …
}
Control Flow - Examples
do-while loop

do {
squared = lo * lo; // Calculate square
System.out.println(squared);
lo = lo + 1; /* Compute the new lo value */
} while (squared <= MAX);
Control Flow - Examples
if-else loop

if ( i < 10) {
System.out.println(“i is less than 10” );
}
else {
System.out.println(“i is greater than or equal to 10”);
}
Control Flow - Examples

switch statement
switch (c) {
case ‘a’:
System.out.println (“ The character is ‘a’” );
break;
case ‘b’;
System.out.println (“ The character is ‘b’” );
break;
default;
System.out.println (“ The character is not ‘a’ or
‘b’” );
break;
}
Command Line Arguments
Command line arguments provide one of the ways for supplying input data at the
time of execution instead of including them in the program. They are supplied as
parameters to the main() method:
public static void main(String args[])
“args” is declared of an array of strings (aka string objects).
args[0] is the first parameter, args[1] is the 2nd argument and so on
The number of arguments passed identified by:
args.length
E.g. count = args.length;
Example Invocation and values:
java MyProgram hello melbourne
args.length will be 2
args[0] will be “hello” and args[1] will be “melborune”
Printing command line arguments
// ComLineTest.java: testing command line arguments
class ComLineTest
{
public static void main(String args[])
{
int count, i = 0;
String myString;
count = args.length;
System.out.println("Number of Arguments = "+count);
while( i < count )
{
myString = args[i];
i = i + 1;
System.out.println(i + " : " + "Java is "+myString+ " !");
}
}
}

+ concatenates strings or numbers


Execution Example
java ComLineTest Simple Object_Oriented Distributed Robust Secure
Portable Multithread Dynamic

The output of program will be:


Number of Arguments = 8
1 : Java is Simple !
2 : Java is Object_Oriented !
3 : Java is Distributed !
4 : Java is Robust !
5 : Java is Secure !
6 : Java is Portable !
7 : Java is Multithread !
8 : Java is Dynamic !
Classes and Objects in Java
Basics of Classes in Java
Contents
Introduce to classes and objects in Java.

Understand how some of the OO concepts


learnt so far are supported in Java.

Understand important features in Java classes.


Introduction
Java is a true OO language and therefore the underlying structure
of all Java programs is classes.
Anything we wish to represent in Java must be encapsulated in a
class that defines the “state” and “behaviour” of the basic
program components known as objects.
Classes create objects and objects use methods to communicate
between them. They provide a convenient method for packaging a
group of logically related data items and functions that work on
them.
A class essentially serves as a template for an object and behaves
like a basic data type “int”. It is therefore important to understand
how the fields and methods are defined in a class and how they
are used to build a Java program that incorporates the basic OO
concepts such as encapsulation, inheritance, and polymorphism.
Classes
A class is a collection of fields (data) and
methods (procedure or function) that operate
on that data.

Circle

centre
radius

circumference()
area()
Classes
A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
The basic syntax for a class definition:

class ClassName [extends


SuperClassName]
{
[fields declaration]
[methods declaration]
}

public class Circle {


// my circle class
}
Adding Fields: Class Circle with fields
Add fields

public class Circle {


public double x, y; // centre coordinate
public double r; // radius of the circle

The fields (data) are also called the instance


varaibles.
Adding Methods
A class with only data fields has no life. Objects created
by such a class cannot respond to any messages.
Methods are declared inside the body of the class but
immediately after the declaration of data fields.
The general form of a method declaration is:

type MethodName (parameter-list)


{
Method-body;
}
Adding Methods to Class Circle

public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
Method Body
return 3.14 * r * r;
}
}
Data Abstraction
Declare the Circle class, have created a new
data type – Data Abstraction

Can define variables (objects) of that type:

Circle aCircle;
Circle bCircle;
Class of Circle cont.
aCircle, bCircle simply refers to a Circle object,
not an object itself.

aCircle bCircle

null null

Points to nothing (Null Reference) Points to nothing (Null Reference)


Creating objects of a class
Objects are created dynamically using the new
keyword.
aCircle and bCircle refer to Circle objects

aCircle = new Circle() ; bCircle = new Circle() ;


Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment After Assignment

aCircle bCircle aCircle bCircle

P Q P Q
Automatic garbage collection
Q
The object does not have a reference
and cannot be used in future.

The object becomes a candidate for automatic


garbage collection.

Java automatically collects garbage


periodically and releases the memory used to
be used in the future.
Accessing Object/Circle Data
Similar to C syntax for accessing data defined
in a structure.

ObjectName.VariableName
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radius


aCircle.y = 2.0
aCircle.r = 1.0
Executing Methods in Object/Circle
Using Object Methods:

sent ‘message’ to aCircle

Circle aCircle = new Circle();

double area;
aCircle.r = 1.0;
area = aCircle.area();
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}

[raj@mundroo]%: java MyMain


Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Using Objects as Parameters

// Objects may be passed to methods.


class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
Classes and Objects in Java
Constructors, Overloading, Static
Members
What is a Constructor?
Constructor is a special method that gets invoked “automatically”
at the time of object creation.
Constructor is normally used for initializing objects with default
values unless different values are supplied.
Constructor has the same name as the class name.
Constructor cannot return values.
A class can have more than one constructor as long as they have
different signature (i.e., different input arguments syntax).
Defining a Constructor
Like any other method
public class ClassName {

// Data Fields…

// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}

//Methods to manipulate data fields


}

Invoking:
There is NO explicit invocation statement
needed: When the object creation statement is
executed, the constructor method will be
executed automatically.
Defining a Constructor: Example

public class Counter {


int CounterIndex;

// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
Trace counter value at each statement and What is the
output ?
class MyClass {
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = counter1.getCounterIndex();
if ( a > b )
counter1.increase();
else
counter1.decrease();

System.out.println(counter1.getCounterIndex());
}
}
A Counter with User Supplied Initial Value ?

This can be done by adding another


constructor method to the class.
public class Counter {
int CounterIndex;

// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}

// A New User Class: Utilising both constructors


Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
Adding a Multiple-Parameters Constructor
to our Circle Class

public class Circle {


public double x,y,r;
// Constructor
public Circle(double centreX, double centreY,
double radius)

{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Constructors initialise Objects
Recall the following OLD Code Segment:

Circle aCircle = new Circle();


aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;
aCircle = new Circle() ;
At creation time the center and
radius are not defined.

These values are explicitly set later.


Constructors initialise Objects
With defined constructor

Circle aCircle = new Circle(10.0, 20.0, 5.0);

aCircle = new Circle(10.0, 20.0, 5.0) ;

aCircle is created with center (10, 20)


and radius 5
Multiple Constructors

Sometimes want to initialize in a number of


different ways, depending on circumstance.

This can be supported by having multiple


constructors having different input
arguments.
Multiple Constructors

public class Circle {


public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double radius) {
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }

//Methods to return circumference and area


public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
Initializing with constructors
public class TestCircles {

public static void main(String args[]){


Circle circleA = new Circle( 10.0, 12.0, 20.0);
Circle circleB = new Circle(10.0);
Circle circleC = new Circle();
}
}

circleA = new Circle(10, 12, 20) circleB = new Circle(10) circleC = new Circle()

Centre = (10,12) Centre = (0,0)


Radius = 20 Centre = (0,0) Radius = 1
Radius=10
Method Overloading
Defining the same method with different
argument types (method overloading)
The method body can have different logic
depending on the date type of arguments.
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.24
Scenario
A Program needs to find a maximum of two numbers or
Strings. Write a separate function for each operation.
In C:
int max_int(int a, int b)
int max_string(char *s1, char *s2)
max_int (10, 5) or max_string (“melbourne”, “sydney”)
In Java:
int max(int a, int b)
int max(String s1, String s2)
max(10, 5) or max(“melbourne”, “sydney”)
Which is better ? Readability and intuitive wise ?
A Program with Method Overloading
// Compare.java: a class comparing different items
class Compare {
static int max(int a, int b)
{
if( a > b)
return a;
else
return b;
}
static String max(String a, String b)
{
if( a.compareTo (b) > 0)
return a;
else
return b;
}

public static void main(String args[])


{
String s1 = "Melbourne";
String s2 = "Sydney";
String s3 = "Adelaide";

int a = 10;
int b = 20;

System.out.println(max(a, b)); // which number is big


System.out.println(max(s1, s2)); // which city is big
System.out.println(max(s1, s3)); // which city is big
}
}
The New this keyword
this keyword can be used to refer to the object itself.
It is generally used for accessing class members (from its own
methods) when they have the same name as those passed as
arguments.

public class Circle {


public double x,y,r;
// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
}
Static Members
Java supports definition of global methods and variables that can
be accessed without creating objects of a class. Such members
are called Static members.
Define a variable by marking with the static methods.
This feature is useful when we want to create a variable common
to all instances of a class.
One of the most common example is to have a variable that could
keep a count of how many objects of a class have been created.
Note: Java creates only one copy for a static variable which can
be used even if the class is never instantiated.
Static Variables
Define using static:

public class Circle {


// class variable, one for the Circle class, how many circles
public static int numCircles;

//instance variables,one for each instance of a Circle


public double x,y,r;
// Constructors...
}

Access with the class name (ClassName.StatVarName):

nCircles = Circle.numCircles;
Static Variables - Example
Using static variables:

public class Circle {


// class variable, one for the Circle class, how many circles
private static int numCircles = 0;
private double x,y,r;

// Constructors...
Circle (double x, double y, double r){
this.x = x;
this.y = y;
this.r = r;
numCircles++;
}
}
Class Variables - Example
Using static variables:

public class CountCircles {

public static void main(String args[]){


Circle circleA = new Circle( 10, 12, 20); // numCircles = 1
Circle circleB = new Circle( 5, 3, 10); // numCircles = 2
}
}

circleA = new Circle(10, 12, 20) circleB = new Circle(5, 3, 10)

numCircles
Instance Vs Static Variables

Instance variables : One copy per object.


Every object has its own instance variable.
E.g. x, y, r (centre and radius in the circle)

Static variables : One copy per class.


E.g. numCircles (total number of circle objects
created)
Static Methods
A class can have methods that are defined as static
(e.g., main method).
Static methods can be accessed without using objects.
Also, there is NO need to create objects.
They are prefixed with keyword “static”
Static methods are generally used to group related
library functions that don’t depend on data members of
its class. For example, Math library functions.
Comparator class with Static methods
// Comparator.java: A class with static data items comparision methods
class Comparator {
public static int max(int a, int b)
{
if( a > b)
return a;
else
return b;
}

public static String max(String a, String b)


{
if( a.compareTo (b) > 0)
return a;
else
return b;
}
}

class MyClass {
public static void main(String args[])
{
String s1 = "Melbourne";
String s2 = "Sydney";
Directly accessed using ClassName (NO Objects)
String s3 = "Adelaide";

int a = 10;
int b = 20;

System.out.println(Comparator.max(a, b)); // which number is big


System.out.println(Comparator.max(s1, s2)); // which city is big
System.out.println(Comparator.max(s1, s3)); // which city is big
}
}
// Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
OUTPUT
Static block initialized.
x = 42
a=3
b = 12
Static methods restrictions
They can only call other static methods.
They can only access static data.
They cannot refer to “this” or “super” (more
later) in anyway.
Introducing Nested and Inner Classes

It is possible to define a class within another class;


such classes are known as nested classes.
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.
Demonstrate an inner class
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
Summary
Constructors allow seamless initialization of objects.
Classes can have multiple methods with the same
name [Overloading]
Classes can have static members, which serve as
global members of all objects of a class.
Keywords: constructors, polymorphism, method
overloading, this, static variables, static methods.
Inheritance
Classes and Subclasses
Or Extending a Class
Inheritance: Introduction
Reusability--building new components by utilising
existing components- is yet another important aspect
of OO paradigm.
It is always good/“productive” if we are able to reuse
something that is already exists rather than creating
the same all over again.
This is achieve by creating new classes, reusing the
properties of existing classes.
Inheritance: Introduction
This mechanism of deriving a
new class from existing/old
class is called “inheritance”.
The old class is known as
“base” class, “super” class or
“parent” class”; and the new Parent
class is known as “sub”
class, “derived” class, or Inherited
capability
“child” class.

Child
Inheritance: Introduction
The inheritance allows subclasses to inherit all
properties (variables and methods) of their parent
classes. The different forms of inheritance are:
Single inheritance (only one super class)
Multiple inheritance (several super classes)
Hierarchical inheritance (one super class, many sub classes)
Multi-Level inheritance (derived from a derived class)
Hybrid inheritance (more than two types)
Multi-path inheritance (inheritance of some properties from two
sources).
Forms of Inheritance
A A B A

B C B C D

(a) Single Inheritance (b) Multiple Inheritance (c) Hierarchical Inheritance

A A
A

B c B c
B

C D D

(a) Multi-Level Inheritance (b) Hybrid Inheritance (b) Multipath Inheritance


Defining a Sub class
A subclass/child class is defined as follows:

class SubClassName extends SuperClassName


{
fields declaration;
methods declaration;
}

The keyword “extends” signifies that the properties of super class


are extended to the subclass. That means, subclass contains its
own members as well of those of the super class. This kind of
situation occurs when we want to enhance properties of existing
class without actually modifying it.
Subclasses and Inheritance
Circle class captures basic properties

For drawing application, need a circle to draw itself


on the screen, GraphicCircle...
This can be realised either by updating the circle
class itself (which is not a good Software
Engineering method) or creating a new class that
builds on the existing class and add additional
properties.
Without Inheritance

public class GraphicCircle {


public Circle c; // keep a copy of a circle

public double area() { return c.area(); }


public double circumference (){ return c.circumference(); }

// new instance variables, methods for this class


public Color outline, fill;
public void draw(DrawWindow dw) { /* drawing code here */ }
}Not very elegant
Subclasses and Inheritance
Circle class captures basic properties
For drawing application need a circle to draw itself
on the screen, GraphicCircle
Java/OOP allows for Circle class code to be
implicitly (re)used in defining a GraphicCircle
GraphicCircle becomes a subclass of Circle,
extending its capabilities
Subclassing

Subclasses created by the keyword


extends:
public class GraphicCircle extends Circle {
// automatically inherit all the variables and methods
// of Circle, so only need to put in the ‘new stuff’

Color outline, fill;


public void draw(DrawWindow dw) {
dw.drawCircle(x,y,r,outline,fill);
}
}

Each GraphicCircle object is also a Circle!


Final Classes
Declaring class with final modifier prevents it
being extended or subclassed.
Allows compiler to optimize the invoking of
methods of the class
final class Cirlce{
…………

}
Subclasses & Constructors

Default constructor automatically calls constructor


of the base class:

default constructor
for Circle class is
called

GraphicCircle drawableCircle = new GraphicCircle();


Subclasses & Constructors

Defined constructor can invoke base class constructor with


super:

public GraphicCircle(double x, double y, double r,


Color outline, Color fill) {
super(x, y, r);
this.outline = outline;
this fill = fill
}
Shadowed Variables

Subclasses defining variables with the same


name as those in the superclass, shadow
them:
Shadowed Variables - Example
public class Circle {
public float r = 100;
}

public class GraphicCircle extends Circle {


public float r = 10; // New variable, resolution in dots per inch
}

public class CircleTest {


public static void main(String[] args){
GraphicCircle gc = new GraphicCircle();
Circle c = gc;
System.out.println(“ GraphicCircleRadius= “ + gc.r); // 10
System.out.println (“ Circle Radius = “ + c.r); // 100
}
}
Overriding Methods

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

class A {
int j = 1;
int f( ) { return j; }
}

class B extends A {
int j = 2;
int f( ) {
return j; }
}
Overriding Methods

class override_test {
public static void main(String args[]) {
B b = new B();
System.out.println(b.j); // refers to B.j prints 2
System.out.println(b.f()); // refers to B.f prints 2
Object Type Casting
A a = (A) b;
System.out.println(a.j); // now refers to a.j prints 1
System.out.println(a.f()); // overridden method still refers to B.f() prints 2 !
}
}

[raj@mundroo] inheritance [1:167] java override_test


2
2
1
2
Using All in One: Person and Student

Person

name: String
sex: char
age: int

Display ( ) : void
Subclass
class. Superclass
class

Student

RollNo: int
Branch: String

Display() : void
Person class: Parent class
// Student.java: Student inheriting properties of person class
class person
{
private String name;
protected char sex; // note protected
public int age;
person()
{
name = null;
sex = 'U'; // unknown
age = 0;
}
person(String name, char sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
String getName()
{
return name;
}
void Display()
{
System.out.println("Name = "+name);
System.out.println("Sex = "+sex);
System.out.println("Age = "+age);

}
}
Student class: Derived class
class student extends person
{
private int RollNo;
String branch;
student(String name, char sex, int age, int RollNo, String branch)
{
super(name, sex, age); // calls parent class's constructor with 3 arguments
this.RollNo = RollNo;
this.branch = branch;
}
void Display() // Method Overriding
{
System.out.println("Roll No = "+RollNo);
System.out.println("Name = "+getName());
System.out.println("Sex = "+sex);
System.out.println("Age = "+age);
System.out.println("Branch = "+branch);
}
void TestMethod() // test what is valid to access
{
// name = "Mark"; Error: name is private
sex = 'M';
RollNo = 20;
}
}

What happens if super class constructor is not explicitly invoked ?


(default constructor will be invoked).
Driver Class
class MyTest
{
public static void main(String args[] )
{
student s1 = new student("Rama", 'M', 21, 1, "Computer Science");
student s2 = new student("Sita", 'F', 19, 2, "Software Engineering");

System.out.println("Student 1 Details...");
s1.Display();
System.out.println("Student 2 Details...");
s2.Display();

person p1 = new person("Rao", 'M', 45);


System.out.println("Person Details...");
p1.Display();

}
}

Can we create Object of person class ?


Output
[raj@mundroo] inheritance [1:154] java MyTest
Student 1 Details...
Roll No = 1
Name = Rama
Sex = M
Age = 21
Branch = Computer Science
Student 2 Details...
Roll No = 2
Name = Sita
Sex = F
Age = 19
Branch = Software Engineering
Person Details...
Name = Rao
Sex = M
Age = 45
[raj@mundroo] inheritance [1:155]
Summary
Inheritance promotes reusability by supporting the
creation of new classes from existing classes.
Various forms of inheritance can be realised in Java.
Child class constructor can be directed to invoke
selected constructor from parent using super keyword.
Variables and Methods from parent classes can be
overridden by redefining them in derived classes.
New Keywords: extends, super, final
Collections
Arrays are used to hold groups of specific type of
items

Collections (container) designed to hold generic


(any) type of objects

Collections let you store, organize and access


objects in an efficient manner.
Final and Abstract Classes
Restricting Inheritance

Parent

Inherited
capability

Child
Final Members: A way for Preventing Overriding of
Members in Subclasses

All methods and variables can be overridden by default


in subclasses.
This can be prevented by declaring them as final using
the keyword “final” as a modifier. For example:
final int marks = 100;
final void display();
This ensures that functionality defined in this method
cannot be altered any. Similarly, the value of a final
variable cannot be altered.
Final Classes: A way for Preventing Classes being
extended

We can prevent an inheritance of classes by other classes by


declaring them as final classes.
This is achieved in Java by using the keyword final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}
Any attempt to inherit these classes will cause an error.
Abstract Classes

When we define a class to be “final”, it cannot be


extended. In certain situation, we want to properties
of classes to be always extended and used. Such
classes are called Abstract Classes.

An Abstract class is a conceptual class.


An Abstract class cannot be instantiated – objects
cannot be created.

Abstract classes provides a common root for a


group of classes, nicely tied together in a package:
Abstract Class Syntax
abstract class ClassName
{
...

abstract Type MethodName1();


Type Method2()
{
// method body
}
}
When a class contains one or more abstract methods, it should be
declared as abstract class.
The abstract methods of an abstract class must be defined in its
subclass.
We cannot declare abstract constructors or abstract static methods.
Abstract Class -Example

Shape is a abstract class.

Shape

Circle Rectangle
The Shape Abstract Class
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}

Is the following statement valid?


Shape s = new Shape();
No. It is illegal because the Shape class is an abstract class, which
cannot be instantiated to create its objects.
Abstract Classes

public Circle extends Shape {


protected double r;
protected static final double PI =3.1415926535;
public Circle() { r = 1.0; )
public double area() { return PI * r * r; }

}
public Rectangle extends Shape {
protected double w, h;
public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }
}
Abstract Classes Properties
A class with one or more abstract methods is
automatically abstract and it cannot be instantiated.
A class declared abstract, even with no abstract
methods can not be instantiated.
A subclass of an abstract class can be instantiated if it
overrides all abstract methods by implementation
them.
A subclass that does not implement all of the
superclass abstract methods is itself abstract; and it
cannot be instantiated.
Summary
If you do not want (properties of) your class to be extended or
inherited by other classes, define it as a final class.
Java supports this is through the keyword “final”.
This is applied to classes.
You can also apply the final to only methods if you do not want
anyone to override them.
If you want your class (properties/methods) to be extended by all
those who want to use, then define it as an abstract class or
define one or more of its methods as abstract methods.
Java supports this is through the keyword “abstract”.
This is applied to methods only.
Subclasses should implement abstract methods; otherwise, they
cannot be instantiated.
Interfaces

Design Abstraction and a way for


loosing realizing Multiple
Inheritance
Interfaces
Interface is a conceptual entity similar to a Abstract
class.
Can contain only constants (final variables) and
abstract method (no implementation) - Different from
Abstract classes.
Use when a number of classes share a common
interface.
Each class should implement the interface.
Interfaces: An informal way of realising multiple
inheritance

An interface is basically a kind of class—it contains


methods and variables, but they have to be only
abstract classes and final fields/variables.
Therefore, it is the responsibility of the class that
implements an interface to supply the code for
methods.
A class can implement any number of interfaces,
but cannot extend more than one class at a time.
Therefore, interfaces are considered as an informal
way of realising multiple inheritance in Java.
Interface - Example

<<Interface>>
Speaker
speak()

Politician Priest Lecturer


speak() speak() speak()
Interfaces Definition
Syntax (appears like abstract class):

interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}
Example:

interface Speaker {
public void speak( );
}
Implementing Interfaces
Interfaces are used like super-classes who
properties are inherited by classes. This is
achieved by creating a class that implements
the given interface as follows:

class ClassName implements InterfaceName [, InterfaceName2, …]


{
// Body of Class
}
Implementing Interfaces Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}

class Priest implements Speaker {


public void speak(){
System.out.println(“Religious Talks”);
}
}

class Lecturer implements Speaker {


public void speak(){
System.out.println(“Talks Object Oriented Design and Programming!”);
}
}
Extending Interfaces
Like classes, interfaces can also be extended. The new
sub-interface will inherit all the members of the
superinterface in the manner similar to classes. This is
achieved by using the keyword extends as follows:

interface InterfaceName2 extends InterfaceName1


{
// Body of InterfaceName2
}
Inheritance and Interface Implementation
A general form of interface implementation:
class ClassName extends SuperClass implements InterfaceName [,
InterfaceName2, …]
{
// Body of Class
}

This shows a class can extended another class while


implementing one or more interfaces. It appears like a multiple
inheritance (if we consider interfaces as special kind of classes
with certain restrictions or special features).
Student Assessment Example
Consider a university where students who participate in the
national games or Olympics are given some grace marks.
Therefore, the final marks awarded = Exam_Marks +
Sports_Grace_Marks. A class diagram representing this scenario
is as follow:

Student Sports

extends

Exam
implements
extends

Results
Software Implementation
class Student
{
// student no and access methods
}
interface Sport
{
// sports grace marks (say 5 marks) and abstract methods
}
class Exam extends Student
{
// example marks (test1 and test 2 marks) and access methods
}
class Results extends Exam implements Sport
{
// implementation of abstract methods of Sport interface
// other methods to compute total marks = test1+test2+sports_grace_marks;
// other display or final results access methods
}
Interfaces and Software Engineering
Interfaces, like abstract classes and methods, provide templates
of behaviour that other classes are expected to implement.
Separates out a design hierarchy from implementation hierarchy.
This allows software designers to enforce/pass common/standard
syntax for programmers implementing different classes.
Pass method descriptions, not implementation
Java allows for inheritance from only a single superclass.
Interfaces allow for class mixing.
Classes implement interfaces.
A Summary of OOP and Java Concepts
Learned So Far
Summary
Class is a collection of data and methods that operate
on that data
An object is a particular instance of a class
Object members accessed with the ‘dot’ (Class.v)
Instance variables occur in each instance of a class
Class variables associated with a class
Objects created with the new keyword
Summary
Objects are not explicitly ‘freed’ or destroyed. Java
automatically reclaims unused objects.
Java provides a default constructor if none defined.
A class may inherit the non-private methods and
variables of another class by subclassing, declaring
that class in its extends clause.
java.lang.Object is the default superclass for a class. It
is the root of the Java hierarchy.
Summary
Method overloading is the practice of defining multiple
methods which have the same name, but different
argument lists
Method overriding occurs when a class redefines a
method inherited from its superclass
static, private, and final methods cannot be overridden
From a subclass, you can explicitly invoke an
overridden method of the superclass with the super
keyword.
Summary
Data and methods may be hidden or encapsulated
within a class by specifying the private or protected
visibility modifiers.
An abstract method has no method body. An abstract
class contains abstract methods.
An interface is a collection of abstract methods and
constants. A class implements an interface by
declaring it in its implements clause, and providing a
method body for each abstract method.
Exceptions:
An OO Way for Handling Errors
Introduction
Rarely does a program runs successfully at its very
first attempt.
It is common to make mistakes while developing as
well as typing a program.
Such mistakes are categorised as:
syntax errors - compilation errors.
semantic errors– leads to programs producing unexpected
outputs.
runtime errors – most often lead to abnormal termination of
programs or even cause the system to crash.
Common Runtime Errors
Dividing a number by zero.
Accessing an element that is out of bounds of an array.
Trying to store incompatible data elements.
Using negative value as array size.
Trying to convert from string data to a specific data value (e.g.,
converting string “abc” to integer value).
File errors:
opening a file in “read mode” that does not exist or no read
permission
Opening a file in “write/update mode” which has “read only”
permission.
Corrupting memory: - common with pointers
Any more ….
Without Error Handling – Example 1

class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
Program does not reach here
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
}
No compilation errors. While running it reports an error and stops without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
Traditional way of Error Handling -
Example 2

class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println(“Result is “ + a/b);
}
Program reaches here
else{
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
Error Handling

Any program can find itself in unusual


circumstances – Error Conditions.

A “good” program should be able to handle


these conditions gracefully.

Java provides a mechanism to handle these


error condition - exceptions
Exceptions

An exception is a condition that is caused


by a runtime error in the program.

Provide a mechanism to signal errors


directly without using flags.

Allow errors to be handled in one central


part of the code without cluttering code.
Exceptions and their Handling
When the JVM encounters an error such as divide by
zero, it creates an exception object and throws it – as a
notification that an error has occurred.
If the exception object is not caught and handled
properly, the interpreter will display an error and
terminate the program.
If we want the program to continue with execution of
the remaining code, then we should try to catch the
exception object thrown by the error condition and
then take appropriate corrective actions. This task is
known as exception handling.
Common Java Exceptions
ArithmeticException
ArrayIndexOutOfBoundException
ArrayStoreException
FileNotFoundException
IOException – general I/O failure
NullPointerException – referencing a null object
OutOfMemoryException
SecurityException – when applet tries to perform an action not
allowed by the browser’s security setting.
StackOverflowException
StringIndexOutOfBoundException
Exceptions in Java
A method can signal an error condition by
throwing an exception – throws
The calling method can transfer control to a
exception handler by catching an exception -
try, catch
Clean up can be done by - finally
Exception Handling Mechanism

try Block

Statements that causes


an exception

Throws
exception
Object

catch Block

Statements that
handle the exception
Syntax of Exception Handling Code


try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
With Exception Handling - Example 3

class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
Program Reaches here
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Finding a Sum of Integer Values Passed as Command
Line Parameters
// ComLineSum.java: adding command line parameters
class ComLineSum
{
public static void main(String args[])
{
int InvalidCount = 0;
int number, sum = 0;

for( int i = 0; i < args.length; i++)


{
try {
number = Integer.parseInt(args[i]);
}
catch(NumberFormatException e)
{
InvalidCount++;
System.out.println("Invalid Number: "+args[i]);
continue;//skip the remaining part of loop
}
sum += number;
}
System.out.println("Number of Invalid Arguments = "+InvalidCount);
System.out.println("Number of Valid Arguments = "+(args.length-InvalidCount));
System.out.println("Sum of Valid Arguments = "+sum);
}
}
Sample Runs
[raj@mundroo] java ComLineSum 1 2
Number of Invalid Arguments = 0
Number of Valid Arguments = 2
Sum of Valid Arguments = 3

[raj@mundroo] java ComLineSum 1 2 abc


Invalid Number: abc
Number of Invalid Arguments = 1
Number of Valid Arguments = 2
Sum of Valid Arguments = 3
Multiple Catch Statements
If a try block is likely to raise more than one type of exceptions, then multiple catch
blocks can be defined as follows:


try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
..
..
catch( Exception-TypeN e)
{
// statements to process exception N
}

finally block
Java supports definition of another block called finally that be used to handle any
exception that is not caught by any of the previous statements. It may be added
immediately after the try block or after the last catch block:

try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
..
..
finally {
….
}
When a finally is defined, it is executed regardless of whether or not an exception is
thrown. Therefore, it is also used to perform certain house keeping operations such
as closing files and releasing system resources.
Catching and Propagating Exceptions

Exceptions raised in try block can be caught


and then they can be thrown again/propagated
after performing some operations. This can be
done by using the keyword “throw” as follows:
throw exception-object;
OR
throw new Throwable_Subclass;
With Exception Handling - Example 4

class WithExceptionCatchThrow{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program Does Not
reach here
catch(ArithmeticException e){
when exception occurs System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
}
With Exception Handling - Example 5

class WithExceptionCatchThrowFinally{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program reaches here catch(ArithmeticException e){
System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
User-Defined Exceptions
Problem Statement :
Consider the example of the Circle class
Circle class had the following constructor
public Circle(double centreX, double centreY,
double radius){
x = centreX; y = centreY; r = radius;
}

How would we ensure that the radius is not zero or negative?


Defining your own exceptions

import java.lang.Exception;
class InvalidRadiusException extends Exception {

private double r;

public InvalidRadiusException(double radius){


r = radius;
}
public void printError(){
System.out.println("Radius [" + r + "] is not valid");
}
}
Throwing the exception

class Circle {
double x, y, r;

public Circle (double centreX, double centreY,


double radius ) throws InvalidRadiusException {
if (r <= 0 ) {
throw new InvalidRadiusException(radius);
}
else {
x = centreX ; y = centreY; r = radius;
}
}
}
Catching the exception

class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(10, 10, -1);
System.out.println("Circle created");
}
catch(InvalidRadiusException e)
{
e.printError();
}
}
}
User-Defined Exceptions in standard format
class MyException extends Exception
{
MyException(String message)
{
super(message); // pass to superclass if parameter is not handled by used defined exception
}
}
class TestMyException {

try {
..
throw new MyException(“This is error message”);
}
catch(MyException e)
{
System.out.println(“Message is: “+e.getMessage());
}
}
}

Get Message is a method defined in a standard


Exception class.
Summary
A good programs does not produce unexpected
results.
It is always a good practice to check for potential
problem spots in programs and guard against program
failures.
Exceptions are mainly used to deal with runtime errors.
Exceptions also aid in debugging programs.
Exception handling mechanisms can effectively used
to locate the type and place of errors.
Summary
Try block, code that could have exceptions / errors
Catch block(s), specify code to handle various types of
exceptions. First block to have appropriate type of
exception is invoked.
If no ‘local’ catch found, exception propagates up the
method call stack, all the way to main()
Any execution of try, normal completion, or catch then
transfers control on to finally block
Packages: Putting Classes Together
Introduction

The main feature of OOP is its ability to support the reuse of


code:
Extending the classes (via inheritance)
Extending interfaces
The features in basic form limited to reusing the classes
within a program.
What if we need to use classes from other programs without
physically copying them into the program under
development ?
In Java, this is achieved by using what is known as
“packages”, a concept similar to “class libraries” in other
languages.
Packages
Packages are Java’s way of grouping a number of related classes
and/or interfaces together into a single unit. That means,
packages act as “containers” for classes.
The benefits of organising classes into packages are:
The classes contained in the packages of other programs/applications
can be reused.
In packages classes can be unique compared with classes in other
packages. That two classes in two different packages can have the
same name. If there is a naming clash, then classes can be accessed
with their fully qualified name.
Classes in packages can be hidden if we don’t want other packages to
access them.
Packages also provide a way for separating “design” from coding.
Java Foundation Packages
Java provides a large number of classes groped into different packages
based on their functionality.
The six foundation Java packages are:
java.lang
Contains classes for primitive types, strings, math functions, threads, and
exception
java.util
Contains classes such as vectors, hash tables, date etc.
java.io
Stream classes for I/O
java.awt
Classes for implementing GUI – windows, buttons, menus etc.
java.net
Classes for networking
java.applet
Classes for creating and implementing applets
Using System Packages
The packages are organised in a hierarchical structure. For
example, a package named “java” contains the package “awt”,
which in turn contains various classes required for implementing
GUI (graphical user interface).

java
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt
Graphics awt Package containing
Font classes
Classes containing
Image
methods

Accessing Classes from Packages
There are two ways of accessing the classes stored in packages:
Using fully qualified class name
java.lang.Math.sqrt(x);
Import package and use class name directly.
import java.lang.Math
Math.sqrt(x);
Selected or all classes in packages can be imported:

import package.class;
import package.*;
Implicit in all programs: import java.lang.*;
package statement(s) must appear first
Creating Packages

Java supports a keyword called “package” for creating user-


defined packages. The package statement must be the first
statement in a Java source file (except comments and white
spaces) followed by one or more classes.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}

Package name is “myPackage” and classes are considred as


part of this package; The code is saved in a file called
“ClassA.java” and located in a directory called “myPackage”.
Creating Sub Packages
Classes in one ore more source files can be part of the same
packages.
As packages in Java are organised hierarchically, sub-
packages can be created as follows:
package myPackage.Math
package myPackage.secondPakage.thirdPackage
Store “thirdPackage” in a subdirectory named “myPackage\
secondPackage”. Store “secondPackage” and “Math” class in a
subdirectory “myPackage”.
Accessing a Package
As indicated earlier, classes in packages can be
accessed using a fully qualified name or using a short-
cut as long as we import a corresponding package.
The general form of importing package is:
import package1[.package2][…].classname
Example:
import myPackage.ClassA;
import myPackage.secondPackage
All classes/packages from higher-level package can be
imported as follows:
import myPackage.*;
Using a Package
Let us store the code listing below in a file named “ClassA.java”
within subdirectory named “myPackage” within the current
directory (say “abc”).

package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body
}
Using a Package
Within the current directory (“abc”) store the
following code in a file named “ClassX.java”

import myPackage.ClassA;

public class ClassX


{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}
Compiling and Running
When ClassX.java is compiled, the compiler compiles it
and places .class file in current directly. If .class of
ClassA in subdirectory “myPackage” is not found, it
comples ClassA also.
Note: It does not include code of ClassA into ClassX
When the program ClassX is run, java loader looks for
ClassA.class file in a package called “myPackage” and
loads it.
Using a Package
Let us store the code listing below in a file named “ClassA.java”
within subdirectory named “secondPackage” within the current
directory (say “abc”).

package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
Using a Package
Within the current directory (“abc”) store the
following code in a file named “ClassX.java”

import myPackage.ClassA;
import secondPackage.ClassC;
public class ClassY
{
public static void main(String args[])
{
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
Output
[raj@mundroo] package % java ClassY

Hello, I am ClassA
Hello, I am ClassC

[raj@mundroo] package %
Protection and Packages
All classes (or interfaces) accessible to all others in the
same package.
Class declared public in one package is accessible
within another. Non-public class is not
Members of a class are accessible from a difference
class, as long as they are not private
protected members of a class in a package are
accessible to subclasses in a different class
Visibility - Revisited
Public keyword applied to a class, makes it
available/visible everywhere. Applied to a method or
variable, completely visible.
Private fields or methods for a class only visible within
that class. Private members are not visible within
subclasses, and are not inherited.
Protected members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.
Visibility Modifiers

Accessible to: public protected Package private


(default)

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass in Yes Yes No No


different package

Non-subclass Yes No No No
different package
Adding a Class to a Package
Consider an existing package that contains a class
called “Teacher”:
package pack1;
public class Teacher
{
// class body
}

This class is stored in “Teacher.java” file within a


directory called “pack1”.
How do we a new public class called “Student” to this
package.
Adding a Class to a Package
Define the public class “Student” and place the package
statement before the class definition as follows:
package pack1;
package pack1;
public class Student class Teacher
{
// class body class Student
}
Store this in “Student.java” file under the directory “pack1”.
When the “Student.java” file is compiled, the class file will be
created and stored in the directory “pack1”. Now, the package
“pack1” will contain both the classes “Teacher” and “Student”.
Packages and Name Clashing
When packages are developed by different organizations, it is
possible that multiple packages will have classes with the same
name, leading to name classing.
package pack1;

class Teacher package pack2;

class Student class Student

We can import and use these packages like: class Courses


import pack1.*;
import pack2.*;
Student student1; // Generates compilation error
Handling Name Clashing
In Java, name classing is resolved by accessing
classes with the same name in multiple packages by
their fully qualified name.
Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;
Extending a Class from Package
A new class called “Professor” can be created
by extending the “Teacher” class defined the
package “pack1” as follows:

import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}
Summary
Packages allow grouping of related classes
into a single united.
Packages are organised in hierarchical
structure.
Packages handle name classing issues.
Packages can be accessed or inherited without
actual copy of code to each program.

You might also like