SlideShare a Scribd company logo
1 of 189
JAVA PROGRAMMING
JAVA BASICS
CSE208- JAVA PROGRAMMING 1
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
2
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
3
PROGRAMMING
Objects
Classes
Data Abstraction
Data Encapsulations
Inheritance
Polymorphism
Dynamic buinding
Message passing
4
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).
5
Features of JAVA
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
6
Java is Compiled and Interpreted
Text Editor Compiler Interpreter
Programmer
Source Code
.java file
Byte Code
.class file
Hardware and
Operating System
Notepad,
emacs,vi
javac java
appletviewer
netscape
7
Total Platform Independence
JAVA COMPILER
JAVA BYTE CODE
JAVA INTERPRETER
Macintosh Solaris Windows NT
(translator)
(same for all platforms)
(one for each different system)
8
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
9
Overlap of C, C++, and Java
C
C++
Java
10
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
11
Java Applications
We can develop two types of Java programs:
Stand-alone applications
Web applications (applets)
12
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”
method
Applet- A program embedded in a web page , to be run
when the page is browsed . A program that contains no
“main” method
13
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”
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.
14
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
15
Process of Building and Running Java Programs
Text Editor
Java Source
Code
javac
Java Class File
java
Outout
javadoc
javah
jdb
HTML Files
Header Files
16
Java Program Structure
Documentation Section
Package Statement
Import Statements
Interface Statements
Class Declarations
Main Method Class
{
}
17
Hello World
// HelloWorld.java: Hello World program
import java.lang.*;
class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
18
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.
19
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()
20
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.
21
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);
}
}
22
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
23
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++)
24
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.
25
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);
}
}
26
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
27
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
28
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
29
Control Flow - Examples
for loop
for (int i = 1; i < MAX; i++)
{
System.out.println(i); // prints 1 2 3 4 5 …
}
30
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
31
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
32
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;
}
33
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”
34
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
35
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 !
36
Classes and Objects in Java
Basics of Classes in Java
CSE208- JAVA PROGRAMMING 37
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.
38
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.
39
Classes
A class is a collection of fields (data) and
methods (procedure or function) that operate
on that data.
Circle
centre
radius
circumference()
area()
40
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:
public class Circle {
// my circle class
}
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
41
Adding Fields: Class Circle with fields
Add fields
The fields (data) are also called the instance
varaibles.
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
42
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;
}
43
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() {
return 3.14 * r * r;
}
}
Method Body
44
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;
45
Class of Circle cont.
aCircle, bCircle simply refers to a Circle object,
not an object itself.
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
46
Creating objects of a class
Objects are created dynamically using the new
keyword.
aCircle and bCircle refer to Circle objects
bCircle = new Circle() ;
aCircle = new Circle() ;
47
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
48
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P
aCircle
Q
bCircle
Before Assignment
P
aCircle
Q
bCircle
After Assignment
49
Automatic garbage collection
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.
Q
50
Accessing Object/Circle Data
Similar to C syntax for accessing data defined
in a structure.
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
51
Executing Methods in Object/Circle
Using Object Methods:
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
52
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
53
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
54
Classes and Objects in Java
Constructors, Overloading, Static
Members
CSE208- JAVA PROGRAMMING 55
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).
56
Defining a Constructor
Like any other method
Invoking:
There is NO explicit invocation statement
needed: When the object creation statement is
executed, the constructor method will be
executed automatically.
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
57
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;
}
}
58
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());
}
}
59
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);
60
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; }
}
61
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.
62
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
63
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.
64
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; }
}
65
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)
Centre = (0,0)
Radius=10
circleC = new Circle()
Centre = (0,0)
Radius = 1
Centre = (10,12)
Radius = 20
66
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.
67
// 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;
}
}
68
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
69
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 ?
70
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
}
}
71
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
}
72
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.
73
Static Variables
Define using static:
Access with the class name (ClassName.StatVarName):
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...
}
nCircles = Circle.numCircles;
74
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++;
}
}
75
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
76
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)
77
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.
78
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";
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
}
}
Directly accessed using ClassName (NO Objects)
79
// 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);
}
}
80
OUTPUT
Static block initialized.
x = 42
a = 3
b = 12
81
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.
82
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.
83
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();
}
}
84
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.
85
Inheritance
Classes and Subclasses
Or Extending a Class
CSE208- JAVA PROGRAMMING 86
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.
87
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
class is known as “sub” class,
“derived” class, or “child”
class.
Parent
Child
Inherited
capability
88
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).
89
Forms of Inheritance
A
B
(a) Single Inheritance
A
C
(b) Multiple Inheritance
B A
C
(c) Hierarchical Inheritance
B D
A
C
(a) Multi-Level Inheritance
B
B
D
(b) Hybrid Inheritance
c
A
B
D
(b) Multipath Inheritance
c
A
90
Defining a Sub class
A subclass/child class is defined as follows:
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.
class SubClassName extends SuperClassName
{
fields declaration;
methods declaration;
}
91
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.
92
Without Inheritance
Not very elegant
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 */ }
}
93
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
94
Subclassing
Subclasses created by the keyword
extends:
Each GraphicCircle object is also a Circle!
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);
}
}
95
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{
…………
}
96
Subclasses & Constructors
Default constructor automatically calls constructor
of the base class:
GraphicCircle drawableCircle = new GraphicCircle();
default constructor
for Circle class is
called
97
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
}
98
Shadowed Variables
Subclasses defining variables with the same
name as those in the superclass, shadow
them:
99
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
}
}
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.
101
Overriding Methods
class A {
int j = 1;
int f( ) { return j; }
}
class B extends A {
int j = 2;
int f( ) {
return j; }
}
102
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
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 !
}
}
Object Type Casting
[raj@mundroo] inheritance [1:167] java override_test
2
2
1
2
103
Using All in One: Person and Student
Person
name: String
sex: char
age: int
Display ( ) : void
Student
RollNo: int
Branch: String
Display() : void
Superclass
class
Subclass
class.
104
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);
}
}
105
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).
106
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 ?
107
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]
108
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
109
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.
110
Final and Abstract Classes
CSE208- JAVA PROGRAMMING 111
Restricting Inheritance
Parent
Child
Inherited
capability
112
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.
113
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.
114
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:
115
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.
116
Abstract Class -Example
Shape is a abstract class.
Shape
Circle Rectangle
117
The Shape Abstract Class
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.
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}
118
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; }
}
119
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.
120
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.
121
Interfaces
Design Abstraction and a way for
loosing realizing Multiple
Inheritance
CSE208- JAVA PROGRAMMING 122
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.
123
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.
124
Interface - Example
speak()
Politician Priest
<<Interface>>
Speaker
speak() speak()
Lecturer
speak()
125
Interfaces Definition
Syntax (appears like abstract class):
Example:
interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method body
}
interface Speaker {
public void speak( );
}
126
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
}
127
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!”);
}
}
128
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
}
129
Inheritance and Interface Implementation
A general form of interface implementation:
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).
class ClassName extends SuperClass implements InterfaceName [,
InterfaceName2, …]
{
// Body of Class
}
130
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
Exam
Results
extends
extends
implements
131
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
}
132
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.
133
A Summary of OOP and Java Concepts
Learned So Far
CSE208- JAVA PROGRAMMING 134
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
135
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.
136
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.
137
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.
138
Exceptions:
An OO Way for Handling Errors
CSE208- JAVA PROGRAMMING 139
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.
140
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 ….
141
Without Error Handling – Example 1
class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
}
Program does not reach here
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)
142
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);
}
else{
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
Program reaches here
143
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
144
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.
145
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.
146
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
147
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
148
Exception Handling Mechanism
try Block
Statements that causes
an exception
catch Block
Statements that
handle the exception
Throws
exception
Object
149
Syntax of Exception Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
150
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);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Program Reaches here
151
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);
}
}
152
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
153
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
}
…
154
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.
155
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;
156
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);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
}
Program Does Not
reach here
when exception occurs
157
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);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
Program reaches here
158
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?
User-Defined Exceptions
159
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");
}
}
160
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;
}
}
}
161
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();
}
}
}
162
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.
163
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.
164
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
165
Packages: Putting Classes Together
CSE208- JAVA PROGRAMMING 166
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.
167
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.
168
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
169
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).
Graphics
Font
java
Image
…
awt
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt Package containing
classes
Classes containing
methods
170
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:
Implicit in all programs: import java.lang.*;
package statement(s) must appear first
import package.class;
import package.*;
171
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 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”.
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
172
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
“myPackagesecondPackage”. Store “secondPackage” and
“Math” class in a subdirectory “myPackage”.
173
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.*;
174
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
}
175
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();
}
}
176
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.
177
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");
}
}
178
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();
}
}
179
Output
[raj@mundroo] package % java ClassY
Hello, I am ClassA
Hello, I am ClassC
[raj@mundroo] package %
180
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
181
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.
182
Visibility Modifiers
Accessible to: public protected Package
(default)
private
Same Class Yes Yes Yes Yes
Class in package Yes Yes Yes No
Subclass in
different package
Yes Yes No No
Non-subclass
different package
Yes No No No
183
Adding a Class to a Package
Consider an existing package that contains a class
called “Teacher”:
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.
package pack1;
public class Teacher
{
// class body
}
184
Adding a Class to a Package
Define the public class “Student” and place the package statement
before the class definition as follows:
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”.
package pack1;
public class Student
{
// class body
}
class Teacher
package pack1;
class Student
185
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.
We can import and use these packages like:
import pack1.*;
import pack2.*;
Student student1; // Generates compilation error
class Teacher
package pack1;
class Student class Student
package pack2;
class Courses
186
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;
187
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.
}
188
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.
189

More Related Content

Similar to JAVA_BASICS.ppt

Introduction
IntroductionIntroduction
Introductionrichsoden
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginersdivaskrgupta007
 
a basic java programming and data type.ppt
a basic java programming and data type.ppta basic java programming and data type.ppt
a basic java programming and data type.pptGevitaChinnaiah
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)ssuser7f90ae
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1sotlsoc
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 featuresshrinath97
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)indiangarg
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 

Similar to JAVA_BASICS.ppt (20)

Introduction
IntroductionIntroduction
Introduction
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
a basic java programming and data type.ppt
a basic java programming and data type.ppta basic java programming and data type.ppt
a basic java programming and data type.ppt
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
java intro.pptx.pdf
java intro.pptx.pdfjava intro.pptx.pdf
java intro.pptx.pdf
 
Java
JavaJava
Java
 
21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)21UCAC31 Java Programming.pdf(MTNC)(BCA)
21UCAC31 Java Programming.pdf(MTNC)(BCA)
 
Java notes
Java notesJava notes
Java notes
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Chapter 2.1
Chapter 2.1Chapter 2.1
Chapter 2.1
 
OOP-Chap2.docx
OOP-Chap2.docxOOP-Chap2.docx
OOP-Chap2.docx
 
Java 9 features
Java 9 featuresJava 9 features
Java 9 features
 
Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)Programming Fundamentals With OOPs Concepts (Java Examples Based)
Programming Fundamentals With OOPs Concepts (Java Examples Based)
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
Java 8
Java 8Java 8
Java 8
 
Mpl 1
Mpl 1Mpl 1
Mpl 1
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 

More from VGaneshKarthikeyan

Unit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptxUnit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptxVGaneshKarthikeyan
 
Linear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptxLinear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptxVGaneshKarthikeyan
 
K-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptxK-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptxVGaneshKarthikeyan
 
Numpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptxNumpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptxVGaneshKarthikeyan
 
Refined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.pptRefined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.pptVGaneshKarthikeyan
 
randomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.pptrandomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.pptVGaneshKarthikeyan
 
stochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.pptstochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.pptVGaneshKarthikeyan
 
1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptxVGaneshKarthikeyan
 
Neural_Networks_scalability_consntency.ppt
Neural_Networks_scalability_consntency.pptNeural_Networks_scalability_consntency.ppt
Neural_Networks_scalability_consntency.pptVGaneshKarthikeyan
 
Lecture-4-Linear Regression-Gradient Descent Solution.ppt
Lecture-4-Linear Regression-Gradient Descent Solution.pptLecture-4-Linear Regression-Gradient Descent Solution.ppt
Lecture-4-Linear Regression-Gradient Descent Solution.pptVGaneshKarthikeyan
 
1.3 Basic coding skills_tupels_sets_controlloops.ppt
1.3 Basic coding skills_tupels_sets_controlloops.ppt1.3 Basic coding skills_tupels_sets_controlloops.ppt
1.3 Basic coding skills_tupels_sets_controlloops.pptVGaneshKarthikeyan
 
Python_basics_tuples_sets_lists_control_loops.ppt
Python_basics_tuples_sets_lists_control_loops.pptPython_basics_tuples_sets_lists_control_loops.ppt
Python_basics_tuples_sets_lists_control_loops.pptVGaneshKarthikeyan
 
1.4 Work with data types and variables, numeric data, string data.pptx
1.4 Work with data types and variables, numeric data, string data.pptx1.4 Work with data types and variables, numeric data, string data.pptx
1.4 Work with data types and variables, numeric data, string data.pptxVGaneshKarthikeyan
 
Inheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridInheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridVGaneshKarthikeyan
 
Refined_Lecture-8-Probability Review-2.ppt
Refined_Lecture-8-Probability Review-2.pptRefined_Lecture-8-Probability Review-2.ppt
Refined_Lecture-8-Probability Review-2.pptVGaneshKarthikeyan
 
Refined_Lecture-13-Maximum Likelihood Estimators-Part-C.ppt
Refined_Lecture-13-Maximum Likelihood Estimators-Part-C.pptRefined_Lecture-13-Maximum Likelihood Estimators-Part-C.ppt
Refined_Lecture-13-Maximum Likelihood Estimators-Part-C.pptVGaneshKarthikeyan
 
Refined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.ppt
Refined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.pptRefined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.ppt
Refined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.pptVGaneshKarthikeyan
 
Bias-Variance_relted_to_ML.pdf
Bias-Variance_relted_to_ML.pdfBias-Variance_relted_to_ML.pdf
Bias-Variance_relted_to_ML.pdfVGaneshKarthikeyan
 
Refined_Lecture-1-Motivation & Applications.ppt
Refined_Lecture-1-Motivation & Applications.pptRefined_Lecture-1-Motivation & Applications.ppt
Refined_Lecture-1-Motivation & Applications.pptVGaneshKarthikeyan
 
Lecture-4-Linear Regression-Gradient Descent Solution.PPTX
Lecture-4-Linear Regression-Gradient Descent Solution.PPTXLecture-4-Linear Regression-Gradient Descent Solution.PPTX
Lecture-4-Linear Regression-Gradient Descent Solution.PPTXVGaneshKarthikeyan
 

More from VGaneshKarthikeyan (20)

Unit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptxUnit III Part I_Opertaor_Overloading.pptx
Unit III Part I_Opertaor_Overloading.pptx
 
Linear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptxLinear_discriminat_analysis_in_Machine_Learning.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptx
 
K-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptxK-Mean clustering_Introduction_Applications.pptx
K-Mean clustering_Introduction_Applications.pptx
 
Numpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptxNumpy_defintion_description_usage_examples.pptx
Numpy_defintion_description_usage_examples.pptx
 
Refined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.pptRefined_Lecture-14-Linear Algebra-Review.ppt
Refined_Lecture-14-Linear Algebra-Review.ppt
 
randomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.pptrandomwalks_states_figures_events_happenings.ppt
randomwalks_states_figures_events_happenings.ppt
 
stochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.pptstochasticmodellinganditsapplications.ppt
stochasticmodellinganditsapplications.ppt
 
1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx1.10 Tuples_sets_usage_applications_advantages.pptx
1.10 Tuples_sets_usage_applications_advantages.pptx
 
Neural_Networks_scalability_consntency.ppt
Neural_Networks_scalability_consntency.pptNeural_Networks_scalability_consntency.ppt
Neural_Networks_scalability_consntency.ppt
 
Lecture-4-Linear Regression-Gradient Descent Solution.ppt
Lecture-4-Linear Regression-Gradient Descent Solution.pptLecture-4-Linear Regression-Gradient Descent Solution.ppt
Lecture-4-Linear Regression-Gradient Descent Solution.ppt
 
1.3 Basic coding skills_tupels_sets_controlloops.ppt
1.3 Basic coding skills_tupels_sets_controlloops.ppt1.3 Basic coding skills_tupels_sets_controlloops.ppt
1.3 Basic coding skills_tupels_sets_controlloops.ppt
 
Python_basics_tuples_sets_lists_control_loops.ppt
Python_basics_tuples_sets_lists_control_loops.pptPython_basics_tuples_sets_lists_control_loops.ppt
Python_basics_tuples_sets_lists_control_loops.ppt
 
1.4 Work with data types and variables, numeric data, string data.pptx
1.4 Work with data types and variables, numeric data, string data.pptx1.4 Work with data types and variables, numeric data, string data.pptx
1.4 Work with data types and variables, numeric data, string data.pptx
 
Inheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybridInheritance_with_its_types_single_multi_hybrid
Inheritance_with_its_types_single_multi_hybrid
 
Refined_Lecture-8-Probability Review-2.ppt
Refined_Lecture-8-Probability Review-2.pptRefined_Lecture-8-Probability Review-2.ppt
Refined_Lecture-8-Probability Review-2.ppt
 
Refined_Lecture-13-Maximum Likelihood Estimators-Part-C.ppt
Refined_Lecture-13-Maximum Likelihood Estimators-Part-C.pptRefined_Lecture-13-Maximum Likelihood Estimators-Part-C.ppt
Refined_Lecture-13-Maximum Likelihood Estimators-Part-C.ppt
 
Refined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.ppt
Refined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.pptRefined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.ppt
Refined_Lecture-15-Dimensionality Reduction-Uunspervised-PCA.ppt
 
Bias-Variance_relted_to_ML.pdf
Bias-Variance_relted_to_ML.pdfBias-Variance_relted_to_ML.pdf
Bias-Variance_relted_to_ML.pdf
 
Refined_Lecture-1-Motivation & Applications.ppt
Refined_Lecture-1-Motivation & Applications.pptRefined_Lecture-1-Motivation & Applications.ppt
Refined_Lecture-1-Motivation & Applications.ppt
 
Lecture-4-Linear Regression-Gradient Descent Solution.PPTX
Lecture-4-Linear Regression-Gradient Descent Solution.PPTXLecture-4-Linear Regression-Gradient Descent Solution.PPTX
Lecture-4-Linear Regression-Gradient Descent Solution.PPTX
 

Recently uploaded

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

JAVA_BASICS.ppt

  • 2. 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 2
  • 3. 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 3
  • 5. 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). 5
  • 7. Java is Compiled and Interpreted Text Editor Compiler Interpreter Programmer Source Code .java file Byte Code .class file Hardware and Operating System Notepad, emacs,vi javac java appletviewer netscape 7
  • 8. Total Platform Independence JAVA COMPILER JAVA BYTE CODE JAVA INTERPRETER Macintosh Solaris Windows NT (translator) (same for all platforms) (one for each different system) 8
  • 9. 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 9
  • 10. Overlap of C, C++, and Java C C++ Java 10
  • 11. 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 11
  • 12. Java Applications We can develop two types of Java programs: Stand-alone applications Web applications (applets) 12
  • 13. 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” method Applet- A program embedded in a web page , to be run when the page is browsed . A program that contains no “main” method 13
  • 14. 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” 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. 14
  • 15. 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 15
  • 16. Process of Building and Running Java Programs Text Editor Java Source Code javac Java Class File java Outout javadoc javah jdb HTML Files Header Files 16
  • 17. Java Program Structure Documentation Section Package Statement Import Statements Interface Statements Class Declarations Main Method Class { } 17
  • 18. Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public static void main(String args[]) { System.out.println(“Hello World”); } } 18
  • 19. 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. 19
  • 20. 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() 20
  • 21. 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. 21
  • 22. 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); } } 22
  • 23. 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 23
  • 24. 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++) 24
  • 25. 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. 25
  • 26. 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); } } 26
  • 27. 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 27
  • 28. 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 28
  • 29. 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 29
  • 30. Control Flow - Examples for loop for (int i = 1; i < MAX; i++) { System.out.println(i); // prints 1 2 3 4 5 … } 30
  • 31. 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 31
  • 32. 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 32
  • 33. 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; } 33
  • 34. 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” 34
  • 35. 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 35
  • 36. 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 ! 36
  • 37. Classes and Objects in Java Basics of Classes in Java CSE208- JAVA PROGRAMMING 37
  • 38. 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. 38
  • 39. 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. 39
  • 40. Classes A class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circle centre radius circumference() area() 40
  • 41. 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: public class Circle { // my circle class } class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] } 41
  • 42. Adding Fields: Class Circle with fields Add fields The fields (data) are also called the instance varaibles. public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle } 42
  • 43. 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; } 43
  • 44. 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() { return 3.14 * r * r; } } Method Body 44
  • 45. 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; 45
  • 46. Class of Circle cont. aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null 46
  • 47. Creating objects of a class Objects are created dynamically using the new keyword. aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ; 47
  • 48. Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; 48
  • 49. Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle After Assignment 49
  • 50. Automatic garbage collection 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. Q 50
  • 51. Accessing Object/Circle Data Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list) 51
  • 52. Executing Methods in Object/Circle Using Object Methods: Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle 52
  • 53. 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 53
  • 54. 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 54
  • 55. Classes and Objects in Java Constructors, Overloading, Static Members CSE208- JAVA PROGRAMMING 55
  • 56. 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). 56
  • 57. Defining a Constructor Like any other method Invoking: There is NO explicit invocation statement needed: When the object creation statement is executed, the constructor method will be executed automatically. public class ClassName { // Data Fields… // Constructor public ClassName() { // Method Body Statements initialising Data Fields } //Methods to manipulate data fields } 57
  • 58. 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; } } 58
  • 59. 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()); } } 59
  • 60. 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); 60
  • 61. 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; } } 61
  • 62. 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. 62
  • 63. 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 63
  • 64. 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. 64
  • 65. 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; } } 65
  • 66. 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) Centre = (0,0) Radius=10 circleC = new Circle() Centre = (0,0) Radius = 1 Centre = (10,12) Radius = 20 66
  • 67. 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. 67
  • 68. // 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; } } 68
  • 69. 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 69
  • 70. 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 ? 70
  • 71. 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 } } 71
  • 72. 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 } 72
  • 73. 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. 73
  • 74. Static Variables Define using static: Access with the class name (ClassName.StatVarName): 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... } nCircles = Circle.numCircles; 74
  • 75. 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++; } } 75
  • 76. 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 76
  • 77. 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) 77
  • 78. 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. 78
  • 79. 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"; 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 } } Directly accessed using ClassName (NO Objects) 79
  • 80. // 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); } } 80
  • 81. OUTPUT Static block initialized. x = 42 a = 3 b = 12 81
  • 82. 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. 82
  • 83. 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. 83
  • 84. 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(); } } 84
  • 85. 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. 85
  • 86. Inheritance Classes and Subclasses Or Extending a Class CSE208- JAVA PROGRAMMING 86
  • 87. 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. 87
  • 88. 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 class is known as “sub” class, “derived” class, or “child” class. Parent Child Inherited capability 88
  • 89. 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). 89
  • 90. Forms of Inheritance A B (a) Single Inheritance A C (b) Multiple Inheritance B A C (c) Hierarchical Inheritance B D A C (a) Multi-Level Inheritance B B D (b) Hybrid Inheritance c A B D (b) Multipath Inheritance c A 90
  • 91. Defining a Sub class A subclass/child class is defined as follows: 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. class SubClassName extends SuperClassName { fields declaration; methods declaration; } 91
  • 92. 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. 92
  • 93. Without Inheritance Not very elegant 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 */ } } 93
  • 94. 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 94
  • 95. Subclassing Subclasses created by the keyword extends: Each GraphicCircle object is also a Circle! 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); } } 95
  • 96. 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{ ………… } 96
  • 97. Subclasses & Constructors Default constructor automatically calls constructor of the base class: GraphicCircle drawableCircle = new GraphicCircle(); default constructor for Circle class is called 97
  • 98. 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 } 98
  • 99. Shadowed Variables Subclasses defining variables with the same name as those in the superclass, shadow them: 99
  • 100. 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 } } 100
  • 101. 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. 101
  • 102. Overriding Methods class A { int j = 1; int f( ) { return j; } } class B extends A { int j = 2; int f( ) { return j; } } 102
  • 103. 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 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 ! } } Object Type Casting [raj@mundroo] inheritance [1:167] java override_test 2 2 1 2 103
  • 104. Using All in One: Person and Student Person name: String sex: char age: int Display ( ) : void Student RollNo: int Branch: String Display() : void Superclass class Subclass class. 104
  • 105. 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); } } 105
  • 106. 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). 106
  • 107. 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 ? 107
  • 108. 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] 108
  • 109. 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 109
  • 110. 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. 110
  • 111. Final and Abstract Classes CSE208- JAVA PROGRAMMING 111
  • 113. 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. 113
  • 114. 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. 114
  • 115. 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: 115
  • 116. 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. 116
  • 117. Abstract Class -Example Shape is a abstract class. Shape Circle Rectangle 117
  • 118. The Shape Abstract Class 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. public abstract class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } } 118
  • 119. 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; } } 119
  • 120. 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. 120
  • 121. 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. 121
  • 122. Interfaces Design Abstraction and a way for loosing realizing Multiple Inheritance CSE208- JAVA PROGRAMMING 122
  • 123. 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. 123
  • 124. 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. 124
  • 125. Interface - Example speak() Politician Priest <<Interface>> Speaker speak() speak() Lecturer speak() 125
  • 126. Interfaces Definition Syntax (appears like abstract class): Example: interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } interface Speaker { public void speak( ); } 126
  • 127. 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 } 127
  • 128. 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!”); } } 128
  • 129. 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 } 129
  • 130. Inheritance and Interface Implementation A general form of interface implementation: 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). class ClassName extends SuperClass implements InterfaceName [, InterfaceName2, …] { // Body of Class } 130
  • 131. 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 Exam Results extends extends implements 131
  • 132. 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 } 132
  • 133. 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. 133
  • 134. A Summary of OOP and Java Concepts Learned So Far CSE208- JAVA PROGRAMMING 134
  • 135. 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 135
  • 136. 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. 136
  • 137. 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. 137
  • 138. 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. 138
  • 139. Exceptions: An OO Way for Handling Errors CSE208- JAVA PROGRAMMING 139
  • 140. 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. 140
  • 141. 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 …. 141
  • 142. Without Error Handling – Example 1 class NoErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; System.out.println(“Result is “ + a/b); System.out.println(“Program reached this line”); } } Program does not reach here 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) 142
  • 143. 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); } else{ System.out.println(“ B is zero); } System.out.println(“Program is complete”); } } Program reaches here 143
  • 144. 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 144
  • 145. 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. 145
  • 146. 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. 146
  • 147. 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 147
  • 148. 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 148
  • 149. Exception Handling Mechanism try Block Statements that causes an exception catch Block Statements that handle the exception Throws exception Object 149
  • 150. Syntax of Exception Handling Code … … try { // statements } catch( Exception-Type e) { // statements to process exception } .. .. 150
  • 151. 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); } catch(ArithmeticException e){ System.out.println(“ B is zero); } System.out.println(“Program reached this line”); } } Program Reaches here 151
  • 152. 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); } } 152
  • 153. 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 153
  • 154. 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 } … 154
  • 155. 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. 155
  • 156. 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; 156
  • 157. 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); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; } System.out.println(“Program is complete”); } } Program Does Not reach here when exception occurs 157
  • 158. 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); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; } finally{ System.out.println(“Program is complete”); } } } Program reaches here 158
  • 159. 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? User-Defined Exceptions 159
  • 160. 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"); } } 160
  • 161. 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; } } } 161
  • 162. 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(); } } } 162
  • 163. 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. 163
  • 164. 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. 164
  • 165. 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 165
  • 166. Packages: Putting Classes Together CSE208- JAVA PROGRAMMING 166
  • 167. 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. 167
  • 168. 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. 168
  • 169. 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 169
  • 170. 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). Graphics Font java Image … awt lang “java” Package containing “lang”, “awt”,.. packages; Can also contain classes. awt Package containing classes Classes containing methods 170
  • 171. 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: Implicit in all programs: import java.lang.*; package statement(s) must appear first import package.class; import package.*; 171
  • 172. 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 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”. package myPackage; public class ClassA { // class body } class ClassB { // class body } 172
  • 173. 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 “myPackagesecondPackage”. Store “secondPackage” and “Math” class in a subdirectory “myPackage”. 173
  • 174. 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.*; 174
  • 175. 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 } 175
  • 176. 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(); } } 176
  • 177. 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. 177
  • 178. 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"); } } 178
  • 179. 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(); } } 179
  • 180. Output [raj@mundroo] package % java ClassY Hello, I am ClassA Hello, I am ClassC [raj@mundroo] package % 180
  • 181. 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 181
  • 182. 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. 182
  • 183. Visibility Modifiers Accessible to: public protected Package (default) private Same Class Yes Yes Yes Yes Class in package Yes Yes Yes No Subclass in different package Yes Yes No No Non-subclass different package Yes No No No 183
  • 184. Adding a Class to a Package Consider an existing package that contains a class called “Teacher”: 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. package pack1; public class Teacher { // class body } 184
  • 185. Adding a Class to a Package Define the public class “Student” and place the package statement before the class definition as follows: 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”. package pack1; public class Student { // class body } class Teacher package pack1; class Student 185
  • 186. 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. We can import and use these packages like: import pack1.*; import pack2.*; Student student1; // Generates compilation error class Teacher package pack1; class Student class Student package pack2; class Courses 186
  • 187. 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; 187
  • 188. 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. } 188
  • 189. 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. 189