0% found this document useful (0 votes)
120 views156 pages

Unit 2: Classes, Inheritance, Packages & Interfaces

The document provides information on object-oriented programming concepts in Java including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It discusses how classes are blueprints for objects, and objects have states and behaviors. Inheritance allows objects to acquire properties of parent objects. Polymorphism allows one task to be performed in different ways. Abstraction hides internal details and shows functionality, while encapsulation binds code and data together into a single unit.

Uploaded by

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

Unit 2: Classes, Inheritance, Packages & Interfaces

The document provides information on object-oriented programming concepts in Java including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It discusses how classes are blueprints for objects, and objects have states and behaviors. Inheritance allows objects to acquire properties of parent objects. Polymorphism allows one task to be performed in different ways. Abstraction hides internal details and shows functionality, while encapsulation binds code and data together into a single unit.

Uploaded by

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

Unit 2

Classes, Inheritance ,Packages &


Interfaces
Chapter 1: Object-Oriented
Programming
• Java is an object-oriented programming language
• As the term implies, an object is a fundamental
entity in a Java program
• Objects can be used effectively to represent real-
world entities
• For instance, an object might represent a
particular employee in a company
• Each employee object handles the processing and
data management related to that employee
• Oriented Programming is a methodology or
paradigm to design a program using classes and
objects. It simplifies the software development and
maintenance by providing some concepts:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Class & Object
• CLASS : Represents the group of similar objects. A class binds the
data & its function together. It has 2 parts.
1.Class Definition –Member Data
2.Class function definitions- Member Functions

• An object is defined by a class


• A class is the blueprint of an object
• The class uses methods to define the behaviors of the object
• The class that contains the main method of a Java program
represents the entire program
• A class represents a concept, and an object represents the
embodiment of that concept
• Multiple objects can be created from the same class
Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or what can be done to it)

• The state of a bank account includes its account


number and its current balance
• The behaviors associated with a bank account
include the ability to make deposits and
withdrawals
• Note that the behavior of an object might change
its state. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
INHERITANCE
• When one object acquires all the properties and behaviors of
parent object i.e. known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.

POLYMORPHISM
• When one task is performed by different ways i.e. known as
polymorphism. For example: to draw something e.g. shape or
rectangle etc.
• In java, we use method overloading and method overriding to
achieve polymorphism.
• Another example ADD operation is used to add integer , float and
string also.

There are two types of polymorphism.


• Compile time polymorphism - It is achieved by overloading
functions and operators
• Run time polymorphism - It is achieved by overriding virtual
functions
ABSTRACTION
• Hiding internal details and showing functionality is
known as abstraction. For example: phone call, we
don't know the internal processing.
• In java, we use abstract class and interface to achieve
abstraction.
ENCAPSULATION
• Binding (or wrapping) code and data together into a
single unit is known as encapsulation. For example:
capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation. Java bean
is the fully encapsulated class because all the data
members are private here.
procedure Oriented programming Object Oriented Programming
Divided Into In POP, program is divided into small In OOP, program is divided into
parts calledf unctions. parts called objects.

Importance In POP,Importance is not given In OOP, Importance is given to the


to data but to functions as well data rather than procedures or
as sequence of actions to be done. functions because it works as a
(Algorithm) real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access Specifiers POP does not have any access specifier. OOP has access specifiers named
Public, Private, Protected, etc.

Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other
through member functions.
Data Access In POP, Most function uses Global In OOP, data can not move easily
data for sharing that can be accessed from function to function, it can
freely from function to function in the be kept public or private so we
system. can control the access of data.
Data Hiding POP does not have any proper way for OOP provides Data Hiding so
hiding data so it is less secure. provides more security.

Overloading In POP, Overloading is not possible. In OOP, overloading is possible in


the form of Function Overloading
and Operator Overloading.
Examples Example of POP are : C, VB, FORTRAN, Example of OOP are : C++, JAVA,
Pascal. VB.NET, C#.NET.
DIFFERENCE BETWEEN STRUCTURE
AND CLASS
STRUCTURE CLASS

Hold only one data contains both function & data


Data members are PUBLIC Members are PRIVATE by
by default default

Members are easily Not easy to access


accessible
Donot support Supports inheritance
inheritance
no such things Members of a class can be
Private, public & private also
ACCESS SPECIFIERS
• CLASS MEMBER VISIBILITY:
1. PRIVATE : The class members(functions &
data) as private can be access only within the
class.(By default its private only)
2 . PUBLIC : Can be accessed from outside the
class
3. PROTECTED: Used in inheritance.
Syntax to declare a class:
class <class_name>{
data member;
method;
}

Simple Example of Object and Class


class Student1{
int id; //data member (also instance variable)
String name; //data member(also instance variable)
void getId(); //member function

public static void main(String args[]){


Student1 s1=new Student1(); //creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
s1.getId();
}
}
Advantage of Method
•Code Reusability
•Code Optimization

new keyword

The new keyword is used to allocate memory at runtime.

The program shows an example to insert values in a record.


class Student2{
int rollno;
String name;

void insertRecord(int r, String n)


{
rollno=r;
name=n;
}
void displayInformation()
{ System.out.println(rollno+" "+name); }

public static void main(String args[])


{
Student2 s1=new Student2();
Student2 s2=new Student2();

s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");

s1.displayInformation();
s2.displayInformation();

} }
class Box { /* assign different values to
double width; mybox2's
double height; instance variables */
double depth; mybox2.width = 3;
} mybox2.height = 6;
mybox2.depth = 9;
class BoxDemo2 {
public static void main(String // compute volume of first box
args[]) { vol = mybox1.width *
Box mybox1 = new Box(); mybox1.height * mybox1.depth;
Box mybox2 = new Box(); System.out.println("Volume is " +
double vol; vol);

// assign values to mybox1's // compute volume of second box


instance variables vol = mybox2.width *
mybox1.width = 10; mybox2.height * mybox2.depth;
mybox1.height = 20; System.out.println("Volume is " +
vol);
mybox1.depth = 15; }}
// This program includes a method inside the box class.
class Box // assign values to mybox1's instance
{ variables
double width; mybox1.width = 10;
double height; mybox1.height = 20;
double depth; mybox1.depth = 15;
// display volume of a box
double volume() /* assign different values to mybox2's
{ instance variables */
System.out.print("Volume is "); mybox2.width = 3;
return(width * height * depth); mybox2.height = 6;
} mybox2.depth = 9;
}
// display volume of first box
class BoxDemo3 { vol=mybox1.volume();
public static void main(String args[]) { System.out.println(vol);
Box mybox1 = new Box();
Box mybox2 = new Box(); // display volume of second box
double vol; vol=mybox2.volume();
System.out.println(vol);
}}
Constructors
• Constructor in java is a special type of method that
is used to initialize the object.
• Java constructor is invoked at the time of object
creation. It constructs the values i.e. provides data
for the object that is why it is known as
constructor.

Rules for creating java constructor


• Constructor name must be same as its class name
• Constructor must have no explicit return type, not
even void.
• Types of java constructors
There are 3 types of constructors:
• Default constructor (no-arg constructor)
• Parameterized constructor
• Copy constructor (object clone)
Default constructors
class Box class BoxDemo6
{ double width; double height; { public static void main(String args[])
double depth; {
// This is the constructor for Box. // declare, allocate, and initialize Box
objects
Box()
Box mybox1 = new Box();
{ System.out.println("Constructing
Box mybox2 = new Box();
Box");
double vol;
width = 10;
// get volume of first box
height = 10;
vol = mybox1.volume();
depth = 10; System.out.println("Volume is " + vol);
} // get volume of second box
// compute and return volume vol = mybox2.volume();
double volume() System.out.println("Volume is "+ vol);
{ return width * height * depth; } }
Parameterized constructor
class Box class BoxDemo {
public static void main(String args[])
{ double width; {
double height; // declare, allocate, and initialize Box
double depth; objects
Box mybox1 = new Box(10, 20, 5);
Box mybox2 = new Box(3, 6, 9);
// This is the constructor for Box.
double vol;
Box(double w, double h, double // get volume of first box
d) vol = mybox1.volume();
{ width = w; height = h; depth = System.out.println("Volume is " +
d; } vol);
// compute and return volume // get volume of second box
vol = mybox2.volume();
double volume()
System.out.println("Volume is " +
{ return width * height * depth; vol);
Copy constructor
Previous program can be extended with passing object of the class
to the constructor itself.
Eg:
Box (Box b)
{
System.out.println(“cloning object”);
}
Public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 5);
Box mybox2 = new Box(mybox1);
//mybox2 is cloned from mybox1 object
}
}
Constructor with different arguments / different number of
arguments are called constructor overloading.
Java program to illustrate Constructor Overloading // compute and return volume
double volume()
class Box {
{ return width * height * depth;
double width, height, depth; }
}
// constructor used when no dimensions specified
Box() // Main code
{ public class Test
width = height = depth = 0; {
public static void main(String args[])
} {
// create boxes using the various constructors
// constructor used when cube is created
Box mybox2 = new Box();
Box(double len)
Box mycube = new Box(7);
{ Box mybox1 = new Box(10, 20, 15);
width = height = depth = len;
} double vol;

// get volume of first box


vol = mybox1.volume();
// constructor used when all dimensions specified System.out.println(" Volume of mybox1 is " + vol);
Box(double w, double h, double d)
// get volume of second box
{ vol = mybox2.volume();
width = w; System.out.println(" Volume of mybox2 is " + vol);
height = h;
// get volume of cube
depth = d; vol = mycube.volume();
} System.out.println(" Volume of mycube is " + vol);
}
}
Method Overloading
• If a class have multiple methods by same name but
different parameters, it is known as Method
Overloading.
• Method overloading increases the readability of the
program.
• 2 ways to differentiate the methods which are
overloaded
1.by number of arguments
2.by data types
1)Example of Method Overloading by
changing the no. of arguments
class Calculation
{
void sum(int a,int b)
{System.out.println(a+b);}
void sum(int a,int b,int c)
{System.out.println(a+b+c);}

public static void main(String args[])


{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);

} }
2)Example of Method Overloading by
changing data type of argument
class Calculation2
{
void sum(int a,int b)
{System.out.println(a+b);}
void sum(double a,double b)
{System.out.println(a+b);
}

public static void main(String args[]) {


Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);

} }
//Write a program to find area of geometrical
figures using method overloading.
public static void main(String arg[])
import java.util.*; {
Scanner sc =new Scanner(System.in);
class geofig
geofig g = new geofig();
{ System.out.println("enter the value for radius of
double area(double r) circle");
double r =sc.nextDouble();
{ System.out.println("area of circle="+g.area(r));
return(3.14*r*r);
} System.out.println("enter the value for side of a
square");
float area(float s) float s =sc.nextFloat();
{ System.out.println("area of square="+g.area(s));
return(s*s); System.out.println("enter the value for length and
} breadth of rectangle");
float area(float l,float b) float l =sc.nextFloat();
float b =sc.nextFloat();
{ System.out.println("area of rectangle="+g.area(l,b));
return(l*b); System.out.println("enter the value for base & height
of triangle");
} double b1 =sc.nextDouble();
double area(double b,double double h =sc.nextDouble();
h) System.out.println("area of triangle="+g.area(b1,h));
{ return(0.5*b*h); }
}
Lab 8:
import java.util.*;
class GarbageCollection
{ public static void main(String s[]) throws Exception
{ Runtime rs = Runtime.getRuntime();
System.out.println("Total memory is: " +
rs.totalMemory());
System.out.println("Free memory in JVM before
Garbage Collection = "+rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after
Garbage Collection = "+rs.freeMemory()); } }
Chapter 2 :Inheritance
• Inheritance in java is a mechanism in which one object
acquires all the properties and behaviors of parent object.
• The idea behind inheritance in java is that you can create
new classes that are built upon existing classes. When you
inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and
fields also.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that you are making a new
class that derives from an existing class.
• In the terminology of Java, a class that is inherited is called a
super class. The new class is called a subclass.
Types of inheritance in java
• On the basis of class, there can be three types of inheritance in java:
single, multilevel and hierarchical.
• In java programming, multiple and hybrid inheritance is supported
through interface only.
When a class extends multiple classes i.e. known as
multiple inheritance which is accomplished using
‘interface’.
// single inheritance
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
} }
Programmer salary is:40000.0
Bonus of programmer is:10000
//Multilevel inheritance
class Employee{
float salary=40000; }
class Programmer extends Employee{
int bonus=10000; }
class Company extends Programmer {
String name=“rana”;
public static void main(String args[]){
Company c =new Company();
System.out.println("Programmer salary is:"+c.salary);
System.out.println("Bonus of Programmer is:"+c.bonus);
System.out.println(“name is” +c.name);
} }
// This program uses inheritance to extend Box. // Here, Box is extended to include weight.
class Box {
class BoxWeight extends Box
double width; double height; double depth;
// construct clone of an object { double weight; // weight of box
Box(Box ob) {
width = ob.width; // constructor for BoxWeight
height = ob.height;
depth = ob.depth; } BoxWeight(double w, double h, double d, double m)
{ width = w; height = h; depth = d; weight = m; }
// constructor used when all dimensions specified }
Box(double w, double h, double d)
class DemoBoxWeight
{ width = w; height = h; depth = d; }
{ public static void main(String args[])
// constructor used when no dimensions specified { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
Box() {
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
width = -1;
height = -1; double vol;
depth = -1;} vol = mybox1.volume();

// constructor used when cube is created


Box(double len) System.out.println("Volume of mybox1 is " + vol);
{ width = height = depth = len; } System.out.println("Weight of mybox1 is " +
mybox1.weight);
// compute and return volume
double volume() { return width * height * depth; } vol = mybox2.volume();
}
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " +
mybox2.weight);
}}
Using super to Call Superclass
Constructors
A subclass can call a construct or defined by its superclass by use of
the following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in
the superclass. super( ) must always be the first statement executed
inside a subclass’ constructor.

// BoxWeight now uses super to initialize its Box attributes.


class BoxWeight extends Box
{ double weight;
// initialize width, height, and depth using super()
BoxWeight (double w, double h, double d, double m)
{ super(w, h, d); // call superclass constructor
weight = m;
}}
super keyword in JAVA
The super keyword in java is a reference variable that
is used to refer immediate parent class object.
Whenever you create the instance of subclass, an
instance of parent class is created implicitly i.e.
referred by super reference variable.
• super is used to refer immediate parent class
instance variable.
• super() is used to invoke immediate parent class
constructor.
• super is used to invoke immediate parent class
method.
A Second Use for super :
General form:
super.member
Here, member can be either a method or an instance
variable. This second form of super is most applicable
to situations in which member names of a subclass
hide members by the same name in the superclass.
Eg:
//example class UseSuper
class A { int i; } {
public static void main(String
// Create a subclass by extending class A
args[])
class B extends A {
int i;
{ B subOb = new B(1, 2);
// this i hides the i in A subOb.show();
}
B(int a, int b) }
{ super.i = a; // i in A
This program displays the
i = b; // i in B
following:
}
i in superclass: 1
void show()
{ System.out.println("i in superclass: " + i in subclass: 2
super.i);
System.out.println("i in subclass: " + i); }
}
//Program of static variable public static void main(String args[
class Student8{ ])
int rollno; {
String name;
Student8 s1 = new Student8(111,“
static String college =“KJC";
AYMAN"); //actual parameters
Student8(int r,String n){ Student8 s2 = new Student8(222,“
// formal parameters HAFSAH");
rollno = r;
name = n; s1.display();
} s2.display();
void display ()
Output:
{
System.out.println(rollno+" "+name 111 AYMAN KJC
+" "+college); 222 HAFSAH KJC
} }
}
STATIC :
The static keyword in java is used for memory
management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The
static keyword belongs to the class than instance of the
class.
The static can be:
• variable (also known as class variable)
• method (also known as class method)
• block
• nested class
The static variable can be used to refer the common
property of all objects .e.g. company name of employees ,
college name of students .
this keyword in java
There can be a lot of usage of java this keyword. In java,
this is a reference variable that refers to the current
object. If the actual and formal parameters uses same
variables ,to differentiate them, this is used.
Usage of java this keyword
• this keyword can be used to refer current class instance
variable.
• this() can be used to invoke current class constructor.
• this keyword can be used to invoke current class
method (implicitly)
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this keyword can also be used to return the current
class instance.
//WITHOUT this KEYWORD //WITH this KEYWORD
class Student11{
class Student10{ int id;
int id; String name;
String name;
Student11(int id,String name)
Student10(int id,String name){ { this.id = id;
id = id; this.name = name;
name = name; }
} void display()
void display() { System.out.println(id+" "+name);}
{System.out.println(id+" "+name);}
public static void main(String args[])
public static void main(String args[]){ { Student11 s1 = new Student11(111,"Ka
Student10 s1 = new Student10(111,"Ka ran");
ran"); Student11 s2 = new Student11(222,"Ar
Student10 s2 = new Student10(321,"Ar yan");
yan"); s1.display();
s1.display(); s2.display();
s2.display(); } }
}
}
Final Keyword In Java
The final keyword in java is used to restrict the user.
The java final keyword can be used in many context.
Final can be:
• variable
• method
• class
The final keyword can be applied with the variables,
a final variable that have no value it is called blank
final variable or uninitialized final variable. If you
make any variable as final, you cannot change the
value of final variable(It will be constant).
FINAL VARIABLE FINAL METHOD
class Bike1{ class Bike2{
final void run()
final int speedlimit=90;//final
{System.out.println("running");}
variable }
void run(){
class Honda extends Bike2{
speedlimit=400;
void run(){
} System.out.println("run safely with 100k
mph");
public static void main(String
}
args[]){
Bike1 obj=new Bike1(); public static void main(String args[]){
Honda honda1= new Honda();
obj.run();
honda1.run();
} }
}//end of class }
ERROR IN COMPILATION
Method Overriding
• 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.
• For example
// Method overriding. class Override
class A { {
int i, j; public static void main(String args[]) {
A(int a, int b) B subOb = new B(1, 2, 3);
{ i = a; j = b; } subOb.show(); // this calls show() in B
// display i and j }
void show() }
{ System.out.println("i and j: " + i + " " + j);
}}

class B extends A
{ int k; The output produced by this program is
B(int a, int b, int c) shown here:
{ super(a, b); k = c; } k: 3
// display k – this overrides show() in A
void show() Method overriding occurs only when the
{ System.out.println("k: " + k); names and the type signatures of the two
methods are identical. If they are not,
} then the two methods are simply
} overloaded
Difference between method Overloading and Overriding in java (compile time
polymorphism and Runtime polymorphism)(static binding and dynamic binding)

• Overloading happens at compile-time while Overriding happens at runtime: The binding of


overloaded method call to its definition has happens at compile-time however binding of
overridden method call to its definition happens at runtime.
• Static methods can be overloaded which means a class can have more than one static
method of same name. Static methods cannot be overridden, even if you declare a same
static method in child class it has nothing to do with the same method of parent class.
• The most basic difference is that overloading is being done in the same class while for
overriding base and child classes are required. Overriding is all about giving a specific
implementation to the inherited method of parent class.
• Static binding is being used for overloaded methods and dynamic bindingis being used for
overridden/overriding methods.
• Performance: Overloading gives better performance compared to overriding. The reason is
that the binding of overridden methods is being done at runtime.
• private and final methods can be overloaded but they cannot be overridden. It means a class
can have more than one private/final methods of same name but a child class cannot
override the private/final methods of their base class.
• Return type of method does not matter in case of method overloading, it can be same or
different. However in case of method overriding the overriding method can have more
specific return type.
• Argument list should be different while doing method overloading. Argument list should be
same in method Overriding.
Using final with Inheritance
• Using final to Prevent Overriding
Methods declared as final cannot be overridden. The
following fragment illustrates final:
class A
{ final void meth()
{ System.out.println("This is a final method."); } }
class B extends A
{ void meth() { // ERROR! Can't override.
System.out.println("Illegal!"); } }
Dynamic Method Dispatch
Method overriding forms the basis for one of Java’s
most powerful concepts: dynamic method dispatch.
Dynamic method dispatch is the mechanism by which
a call to an overridden method is resolved at run
time, rather than compile time.
Dynamic method dispatch is important because this
is how Java implements run-time polymorphism.
If we need to use the super class methods overridden
by the subclass without changing them ,the conflict
has to be solved during the runtime by creating the
reference variable for each superclass object.
LAB 5 class FindAreas
// Using run-time polymorphism. { public static void main(String args[])
class Figure { { Figure f = new Figure(10, 10);
double dim1; double dim2; Rectangle r = new Rectangle(9, 5);
Figure(double dim1, double dim2) Triangle t = new Triangle(10, 8);
{ this.dim1 = dim1; this.dim2 = dim2; }
Figure figref;
double area() figref = r; System.out.println("Area is " +
{ System.out.println("Area for Figure is undefined."); figref.area());
return 0; } figref = t; System.out.println("Area is " +
} figref.area());
class Rectangle extends Figure figref = f; System.out.println("Area is " +
figref.area());
{ Rectangle(double dim1, double dim2)
}
{ super(dim1, dim2); }
}
// override area for rectangle
The output from the program is shown here:
double area()
Inside Area for Rectangle.
{ System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; } Area is 45
} Inside Area for Triangle.
Area is 40
class Triangle extends Figure Area for Figure is undefined.
{ Triangle(double dim1, double dim2) Area is 0
{ super(dim1, dim2); }

// override area for right triangle


double area()
{ System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2; }
}
// Dynamic Method Dispatch class Dispatch
class A { public static void main(String args[])
{ {
void callme() A a = new A(); // object of type A
{ System.out.println("Inside A's callme B b = new B(); // object of type B
method"); C c = new C(); // object of type C
}} A r; // obtain a reference of type A

class B extends A r = a; // r refers to an A object


{ // override callme() r.callme(); // calls A's version of callme
void callme()
{ System.out.println("Inside B's callme r = b; // r refers to a B object
method"); } } r.callme(); // calls B's version of callme

class C extends A r = c; // r refers to a C object


{ // override callme() r.callme(); // calls C's version of callme
void callme() }}
{ System.out.println("Inside C's callme
method"); } } The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
Abstract class in Java
• A class that is declared with abstract keyword, is known
as abstract class in java. It can have abstract and non-
abstract methods (method with body).
• Abstraction is a process of hiding the implementation
details and showing only functionality to the user.
• To define a superclass that declares the structure of a
given abstraction without providing a complete
implementation of every method.
• A general template/structure is given to the subclasses
by the superclass.
• The definition of the abstract method is given by the
subclasses separately.
// Using abstract methods and classes. class AbstractAreas
abstract class Figure { public static void main(String args[])
{ double dim1; double dim2; { // Figure f = new Figure(10, 10); // illegal now

Figure(double a, double b) Rectangle r = new Rectangle(9, 5);


{ dim1 = a; dim2 = b; } Triangle t = new Triangle(10, 8);
// area is now an abstract method
abstract double area(); Figure figref; // this is OK, no object is created
} figref = r;
System.out.println("Area is " + figref.area());
class Rectangle extends Figure
{ Rectangle(double a, double b) figref = t;
{ super(a, b); } System.out.println("Area is " + figref.area());
}
// override area for rectangle }
double area()
{ System.out.println("Inside Area for Rectangle.");
return dim1 * dim2; }
}

class Triangle extends Figure


{ Triangle(double a, double b)
{ super(a, b); }

// override area for right triangle


double area() { System.out.println("Inside Area for
Triangle."); return dim1 * dim2 / 2; }
}
chapter:3 Interface
• To implement an interface, a class must create the
complete set of methods defined by the interface.
However, each class is free to determine the details
of its own implementation. By providing the
interface keyword, Java allows you to fully utilize
the “one interface, multiple methods” aspect of
polymorphism.
• An interface in java is a blueprint of a class. It has
static constants and abstract methods only.
• The interface in java is a mechanism to achieve
fully abstraction. There can be only abstract
methods in the java interface not method body. It is
used to achieve fully abstraction and multiple
inheritance in Java.
• It cannot be instantiated just like abstract class.
• There are mainly three reasons to use interface.
They are given below.
• It is used to achieve fully abstraction.
• By interface, we can support the functionality of
multiple inheritance.
• It can be used to achieve loose coupling.
• interface is the code that is used to create an interface in java.
• We can’t instantiate an interface in java.(ie) create object for
interface.
• abstract classes can have method implementations but interface
can’t.
• Interfaces can’t have constructors because we can’t instantiate
them and interfaces can’t have a method with body.
• By default any attribute of interface is public, static and final, so
we don’t need to provide access modifiers to the attributes but if
we do, compiler doesn’t complain about it either.
• By default interface methods are implicitly abstract and public, it
makes total sense because the method don’t have body and so
that subclasses can provide the method implementation.
• An interface can’t extend any class but it can extend another
interface. Actually java provides multiple inheritance in interfaces,
what it means is that an interface can extend multiple interfaces.
• implements keyword is used by classes to implement an interface.
• A class implementing an interface must provide implementation
for all of its method unless it’s an abstract class.
Defining an Interface
• An interface is defined much like a class. This is the
general form of an interface:

access interface name {


return-type method-name1(parameter-list);
type final-varname1 = value;
}
Variables can be declared inside of interface declarations .
They are implicitly final and static, meaning they cannot
be changed by the implementing class.
They must also be initialized. All methods and variables
are implicitly public.
Example
interface Callback
{
void callback(int param);
}
• A class can extend another class and implement the
interfaces also ,to achieve multiple interface.
Ex: class A extends B implements interface1,interface2
• One interface can extend another interface.
Ex: interface inf1 extends inf2
Implementing Interfaces
• Once an interface has been defined, one or more
classes can implement that interface.
• To implement an interface, include the implements
clause in a class definition, and then create the
methods defined by the interface.
• The general form of a class that includes the
implements clause looks like this:
• class classname [extends superclass] [implements
interface [,interface...]] { // class-body }
• This supports multiple inheritance . since it is
acquiring the properties from the parent class and
interface .
interface Shape public double volume()
{ { return x * y *z; }
public double area(); void print()
public double volume(); {
} System.out.println("point: " +
public class Point implements x + "," + y + “,” + z); }
Shape public static void main(String
{ static int x, y , z; args[])
public Point() {
{ x = 0; y = 0;z=0; } Point p = new Point();
public double area() p.area(); p.volume();
{ return x * y; } p.print();
}}
Interfaces Can Be Extended
One interface can inherit another by use of the
keyword extends.
The syntax is the same as for inheriting classes. When
a class implements an interface that inherits
another interface, it must provide implementations
for all methods defined within the interface
inheritance chain.
// One interface can extend public void meth2() {
another. System.out.println("Implement
interface A { meth2().");
void meth1(); }
void meth2(); public void meth3() {
}
// B now includes meth1() and System.out.println("Implement
meth2() -- it adds meth3(). meth3().");
interface B extends A { }
void meth3(); }
} class IFExtend {
// This class must implement all of public static void main(String arg[])
A and B {
class MyClass implements B { MyClass ob = new MyClass();
public void meth1() { ob.meth1();
System.out.println("Implement ob.meth2();
meth1()."); ob.meth3();
} }
}
Interface implemented in abstract class
Interface A Void add()
{ {System.out.println(“hai”);
Void add(); }
Void mul();
} Void mul()
Interface B {
{ System.out.println(“hru”);
Void print(); }
} }
Class parent implements A
{ Class child extends parent implements B
Int xx,yy; {
Void calc() void display()
{ { xx = xx + 1;
System.out.println(xx ,yy); System.out.println( xx);
} }
void print() public class main1
{ System.out.println(“welcome”); } {
} Public static class main(String
args[])
abstract class child1 implements A {
{ int a,b,c; Child c= new child();
Void add() c.display();
{ c.print();
c= a+b; c.calc();
System.out.println(c);
}} Child1 c1 =new c1();
C1.add();
}}
public interface Shape { public class Circle implements Shape {
//implicitly public, static and
final private double radius;
public String LABEL="Shape";
public Circle(double r)
//interface methods are
{ this.radius = r; }
implicitly abstract and
public void draw(); public void draw() {
double getArea(); System.out.println("Drawing Circle");
} }

public abstract class public double getArea()


{ return Math.PI*this.radius*this.radius;
ShapeAbs implements Shape
}
{
public double getArea() public double getRadius()
{ return 0; } { return this.radius; }
} }
public class Rectangle implements Shape public class ShapeTest {
{
public static void main(String[] args) {
private double width;
private double height; //programming for interfaces not
implementation
public Rectangle(double w, double h){ Shape s = new Circle(10);
this.width=w;
this.height=h; s.draw();
} System.out.println("Area="+s.getArea());

public void draw() { //switching from one implementation


System.out.println("Drawing to another easily
Rectangle"); s=new Rectangle(10,10);
} s.draw();
System.out.println("Area="+s.getArea());
public double getArea() { }
return this.height*this.width;
} }
}
Chapter:4 packages
• A java package is a group of similar types of classes,
interfaces and sub-packages.
• Package in java can be categorized in two form, built-in
package and user-defined package.
• There are many built-in packages such as java, lang, awt,
javax, swing, net, io, util, sql etc.
• Here, we will have the detailed learning of creating and using
user-defined packages.

Advantage of Java Package


• 1) Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
• 2) Java package provides access protection.
• 3) Java package removes naming collision.
Chapter 4-Packages
• 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.
67
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
68 coding.
Java Foundation Packages
(API)
• 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
69
• Classes for creating and implementing applets
Using System Packages
• The packages are organised in a hierarchical structure. For
example, a package named “java” contains the package “awt”,
which in turn contains various classes required for
implementing GUI (graphical user interface).

java
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt
Graphics awt Package containing
Font classes
Classes containing
Image
methods
70 …
Accessing Classes from Packages
• There are two ways of accessing the classes stored in packages:
– Using fully qualified class name
• java.lang.Math.sqrt(x);
– Import package and use class name directly.
• import java.lang.Math
• Math.sqrt(x);
• Selected or all classes in packages can be imported:

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

71
Creating Packages
• Java supports a keyword called “package” for creating user-
defined packages. The package statement must be the first
statement in a Java source file (except comments and white
spaces) followed by one or more classes.

package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}

• Package name is “myPackage” and classes are considred as


part of this package; The code is saved in a file called
“ClassA.java” and located in a directory called “myPackage”.
72
Creating Sub Packages
• Classes in one or 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.secondPackage.thirdPackage;

• Store “thirdPackage” in a subdirectory named


“myPackage\secondPackage”. Store “secondPackage” and
“Math” class in a subdirectory “myPackage”.

73
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.*;

74
volatile
• The Java volatile keyword is used to mark a Java
variable as "being stored in main memory". More
precisely that means, that every read of a volatile
variable will be read from the computer's main
memory, and not from the CPU cache, and that
every write to a volatile variable will be written to
main memory, and not just to the CPU cache.
Example:
public class SharedObject
{ public volatile int counter = 0; }
Volatile keyword tells the compiler that the variable
can be changed unexpectedly by other parts of the
program.
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 “13cs210”).

package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body
}
76
Using a Package
• Within the current directory (“14cs310”) 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();
}
}

77
Steps to create a package
1.Declare the package at the beginning of a file using
the form package packagename;
2.Define the class that is to be put in the package and
declare in public.
3.Create a subdirectory under the directory where the
main source files are stored.
4.Store the listing as the classnam.java file in the
subdirectory created.
5.Compile the file . This creates .class file in the
subdirectory.
78
Compiling and Running
• When ClassX.java is compiled, the compiler compiles
it and places .class file in current directory. If .class of
ClassA in subdirectory “myPackage” is not found, it
compiles 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.

79
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 “13cs201”).

package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
80
Using a Package
• Within the current directory (“13cs201”) 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();
}
81 }
Output
Hello, I am ClassA
Hello, I am ClassC

82
Package example
Package is created Package is implemented
package myPackage; import myPackage.ClassA;
public class ClassA { public class ClassX
// class body {public static void main(String
public void display() args[])
{ {
System.out.println("Hello, I am ClassA objA = new ClassA();
ClassA"); objA.display();
} }
} }
class ClassB {
// class body
}
83
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

84
Example 2
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
To Compile: javac -d . Simple.java

To Run: java mypack.Simple


85
Example 3
//save by A.java
package pack;
public class A{
public void msg()
{System.out.println("Hello");}}

//save by B.java
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg(); }}

• Output:Hello

86
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.

87
Visibility Modifiers
Accessible to: public protected Package private
(default)

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass in Yes Yes No No


different package

Non-subclass Yes No No No
different package

88
Adding a Class to a Package
• Consider an existing package that contains a class called
“Teacher”:

package pack1;
public class Teacher
{
// class body
}
• This class is stored in “Teacher.java” file within a
directory called “pack1”.
• How do we a new public class called “Student” to this
package.
89
package pack1;

Adding a Class to a Package class Teacher

class Student

• Define the public class “Student” and place the package


statement before the class definition as follows:

package pack1;
public class Student
{
// class body
}

• 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”.
90
Packages and Name Clashing
• When packages are developed by different organizations, it is
possible that multiple packages will have classes with the
same name, leading to name classing.
package pack1; package pack2;

class Teacher class Student

class Student class Courses


• We can import and use these packages like:
– import pack1.*;
– import pack2.*;
– Student student1; // Generates compilation error

91
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;

92
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.
}

93
Accessing Using Package Members
The types that comprise a package are known as the
package members. There are 3 ways to access a
package :
1. Refer to the member by its fully
qualified name
2. Import the package member
3. Import the member's entire package
Each is appropriate for different situations.
1.Referring to a Package Member by Its Qualified Name
If you are trying to use a member from a different package
and that package has not been imported, you must use the
member's fully qualified name, which includes the package
name.
example.
graphics.Rectangle
• You could use this qualified name to create an instance
of graphics.Rectangle:
graphics.Rectangle myRect = new graphics.Rectangle();
• Qualified names are all right for infrequent use. When a
name is used repetitively, however, typing the name
repeatedly becomes tedious and the code becomes
difficult to read. As an alternative, you can import the
member or its package and then use its simple name.
2. Importing a Package Member
• To import a specific member into the current file, put
an import statement at the beginning of the file before
any type definitions but after the package statement, if
there is one. Here's how you would import the
Rectangle class from the graphics package created in
the previous section.
import graphics.Rectangle;
• Now you can refer to the Rectangle class by its simple
name.
Rectangle myRectangle = new Rectangle();

• This approach works well if you use just a few members


from the graphics package. But if you use many types
from a package, you should import the entire package.
3. Importing an Entire Package
• To import all the types contained in a particular
package, use the import statement with the asterisk (*)
wildcard character.
import graphics.*;
• Now you can refer to any class or interface in the
graphics package by its simple name.
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();
• The asterisk in the import statement can be used only
to specify all the classes within a package, as shown
here. It cannot be used to match a subset of the classes
in a package. For example, the following does not
match all the classes in the graphics package that begin
with A.
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.

98
synchronised
• Synchronized block can be used to perform
organized execution on any specific resource of the
method.
• Synchronized block is used to lock an object for any
shared resource.
• Scope of synchronized block is smaller than the
method.
• Syntax to use synchronized block
synchronized (object reference expression) {
//code block
}
Java Inner Class
• Java inner class or nested class is a class i.e. declared inside the class or interface.
• Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code } }
• Advantage of java inner classes
There are basically three advantages of inner classes in java.
They are as follows:
1) Nested classes represent a special type of relationship that is
it can access all the members (data members and methods) of
outer class including private.
2) Nested classes are used to develop more readable and
maintainable code because it logically group classes and
interfaces in one place only.
3) Code Optimization: It requires less code to write.
Finalize
• Finalize is a method.
• Finalize is used to perform clean up processing just before object is
garbage collected.
class FinalizeExample{
public void finalize()
{
System.out.println("finalize called");
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}}
Differentiate final ,finally ,finalize
No
final finally finalize
.

Final is used to apply


Finally is used to
restrictions on class, method Finalize is used to
place important
and variable. Final class can't perform clean up
code, it will be
1) be inherited, final method processing just before
executed whether
can't be overridden and final object is garbage
exception is handled
variable value can't be collected.
or not.
changed.

2) Final is a keyword. Finally is a block. Finalize is a method.


Basic java packages

Java.lang, Java.util, java.io, java.awt,


java.applet
The java.lang Package
java.lang overview
• Object
• Math
• The wrapper classes
• String
• StringBuffer
java.lang.Object
• Class Object is the root of the class hierarchy.
• Every class has Object as a superclass.
• All objects, including arrays, implement the
methods of this class.
• If a class doesn’t extend another class, then
compiler extends it from Object.
• For instance:
public class example { // methods}

is created by the compiler as:


public class example extends Object{ // methods}
java.lang.Object
• Cloneable
– A class implements the Cloneable interface to indicate to the clone method in class Object that it is
legal for that method to make a field-for-field copy of instances of that class.

• SecurityManager
– The security manager is an abstract class that allows applications to implement a security policy

• Exceptions
– The class Exception and its subclasses are a form of Throwable that indicates conditions that a
reasonable application might want to catch.

• Errors
– An Error is a subclass of Throwable that indicates serious problems that a reasonable application
should not try to catch. Most such errors are abnormal conditions

• ClassLoader
– The class ClassLoader is an abstract class. Applications implement subclasses of ClassLoader in
order to extend the manner in which the Java Virtual Machine dynamically loads classes.
java.lang.Object Methods
• Thread control
– wait(), notify(), notifyAll()
• General
– equals(), toString()
• Not tested
– finalize(), hashCode(), clone(), getClass()
java.lang.Math
• The class Math contains methods for
performing basic numeric operations such as
the elementary exponential, logarithm, square
root, and trigonometric functions.
• class is final
• constructor is private
• methods are static
java.lang.Math (con’t)

int, long, float, abs() Returns absolute


double value
int, long, float, max(x1, x2) Returns the
double greater of x1
and x2
int, long, float, min( x1, x2) Returns the
double smaller of x1
and x2
java.lang.Math (con’t)
• double sin( double d )
– returns the sine of d
• double cos( double d )
– returns the cosine of d
• double tan( double d )
– returns the tangent of d
• double sqrt( double d )
– returns the square root of d
java.lang Wrapper Classes
Primitive Data Type Wrapper Class
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double

Each of Java's eight primitive data types has a class dedicated to it. These
are known as wrapper classes, because they "wrap" the primitive data
type into an object of that class. So, there is an Integer class that holds
an int variable, there is a Double class that holds a double variable, and
so on.
The following declaration creates an Integer object which represents
the integer 40 as an object
Integer age = new Integer(40);
Discuss this syntax…
Creates an object, age, of type Integer and
gives it an initial value of 40. (Constructor
assigns value of 40 as part of its
initialization – later)
An object of a wrapper class can be used in any situation where a
primitive value will not suffice
For example, some objects serve as containers of other objects
Primitive values could not be stored in such containers, but wrapper
objects could be
java.lang Wrapper Classes
• encapsulates a single, immutable value
• all wrapper classes can be constructed by passing the
value to be wrapper to the constructor
– double d = 453.2344;
– Double myDouble = new Double( d );
• can also pass Strings that represent the value to be
wrapped (doesn’t work for Character)
– Short myShort = new Short( “2453” );
– throws NumberFormatException
Wrapper classes also contain static methods that help manage
the associated type
For example, the Integer class contains a method to convert
an integer stored in a String to an int value:

int num;

num = Integer.parseInt(str);

Or

float fltnum;

fltnum = Float.parseFloat(str);

If the input is of the form 13.2, that is


nn.nn.
The Integer Class
• Convert to different types
byte byteValue() static String toBinaryString(int value)
double doubleValue()
static String toHexString(int value)
float floatValue()
int intValue() static String toOctalString(int value)
long longValue() static String toString(int value)
short shortValue() static String toString(int value, int radix)
String toString()
• Parse integer strings
static Integer decode(String s)
static int parseInt(String s)
static int parseInt(String s, int radix)
static Integer valueOf(String s)
static Integer valueOf(String s, int radix)

116
java.lang.String
• uses 16-bit Unicode characters
• represents an immutable string
• Java programs have a pool of literals
– when a String literal is created, it is created in the
pool
– if the value already exists, then the existing
instance of String is used
– both == and equals() work
java.lang.String
• uses 16-bit Unicode characters
• represents an immutable string
• Java programs have a pool of literals
– when a String literal is created, it is created in the
pool
– if the value already exists, then the existing
instance of String is used
– both == and equals() work
.equals() and ==
• Note this example:
String s1 = “test”;
String s2 = “test”;
s1 == s2; // returns true
s1.equals( s2 ); // returns true

String s3 = “abc”;
String s4 = new String( s3 );
s3 == s4; // returns false
s3.equals( s4 ); // returns true
String methods
• char charAt( int index)
• String concat( String addThis )
• int compareTo( String otherString )
• boolean endsWith( String suffix )
• boolean equals( Object obj )
• boolean equalsIgnoreCase( String s )
• int indexOf( char c )
• int lastIndexOf( char c )
• int length()
• String replace( char old, char new )
• boolean startsWith( String prefix )
• String substring( int startIndex )
• String toLowerCase()
• String toString()
• String toUpperCase()
• String trim()
• remember: Strings are immutable so these methods
return new Strings instead of altering itself
java.lang.StringBuffer
• represents a String which can be modified
• has a capacity, which can grow dynamically
• StringBuffer append( String s )
• StringBuffer append( Object obj )
• StringBuffer insert( int offset, String s )
• StringBuffer reverse()
• StringBuffer setCharAt( int offset, char c )
• StringBuffer setLength( int newlength )
• String toString()
Java.Util
Date
Calender
Random
Introduction
The java.util.Date class represents a specific instant in time, with millisecond
precision.
Class declaration
Following is the declaration for java.util.Date class:
public class Date extends Object implements Serializable, Cloneable,
Comparable<Date>
Class constructors
S.N. Constructor & Description
Date()
This constructor allocates a Date object and initializes it
1
so that it represents the time at which it was allocated,
measured to the nearest millisecond.
Date(long date)
This constructor allocates a Date object and initializes it
2 to represent the specified number of milliseconds since
the standard base time known as "the epoch", namely
January 1, 1970, 00:00:00 GMT.
Class methods
S.N. Method & Description
1
boolean after(Date when)
This method tests if this date is after the specified date.
2
boolean before(Date when)
This method tests if this date is before the specified date.
3
Object clone()
This method return a copy of this object.
4
int compareTo(Date anotherDate)
This method compares two Dates for ordering.
5
boolean equals(Object obj)
This method compares two dates for equality.
long getTime()
6 This method returns the number of milliseconds since January 1, 1970,
00:00:00 GMT represented by this Date object.
7
int hashCode()
This method returns a hash code value for this object.
void setTime(long time)
8 This method sets this Date object to represent a point in time that is time
milliseconds after January 1, 1970 00:00:00 GMT.
9
String toString()
This method converts this Date object to a String of the form.
Show date and time using only Date methods.

import java.util.Date;

class DateDemo {
public static void main(String args[]) {
Date date1 = new Date();

System.out.println(date1);

long msec = date1.getTime();


System.out.println("Milliseconds since Jan. 1, 1970 GMT = " +
msec);
}
}
import java.util.*;

class GetCurrentDateAndTime
{
public static void main(String args[])
{
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();

day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);

second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);

System.out.println("Current date is "+day+"/"+(month+1)+"/"+year);


System.out.println("Current time is "+hour+" : "+minute+" : "+second);
}
}
Create java Date from specific time example

import java.util.Date;

public class Main {


public static void main(String[] args) {
Date d = new Date(365L * 24L * 60L * 60L * 1000L);
System.out.println(d);
}
}
UTIL.CALENDER PACKAGE
Class declaration
Following is the declaration for java.util.Calendar class:
public abstract class Calendar extends Object implements Serializable, Cloneable,
Comparable<Calendar>

METHODS DESCRIPTION
abstract void add(int which, int val) Adds val to the time or date component
specified by which. To subtract, add a negative
value. Which must be one of the fields defined
by Calendar, such as Calendar.HOUR.
boolean after(Object calendarObj) Returns true if the invoking Calendar object
boolean before(Object calendarObj) contains a date that is later/EARLIER than the
one specified by calendarObj. Otherwise, it
returns false.
final void clear( ) Zeros all time components in the invoking
final void clear(int which) object.
Zeros the time component specified by which
in the invoking object.
Object clone( ) Returns a duplicate of the invoking object.
boolean equals(Object calendarObj) Returns true if the invoking Calendar object
contains a date that is equal to the one
specified
ALL_STYLES FRIDAY PM DAY_OF_WEEK MARCH DECEMBER MINUTE
AM HOUR SATURDAY TUESDAY WEEK_OF_MONTH
AM_PM HOUR_OF_DAY SECOND DAY_OF_WEEK_IN_MON DST_OFFSET MONDAY
APRIL JANUARY SEPTEMBER TH MAY UNDECIMBER WEEK_OF_YEAR
AUGUST JULY SHORT DAY_OF_YEAR ERA MONTH YEAR
DATE JUNE SUNDAY MILLISECOND FEBRUARY NOVEMBER
DAY_OF_MONTH LONG THURSDAY WEDNESDAY ZONE_OFFSET
FIELD_COUNT OCTOBER

REFER THE FOLLOWING URL FOR MORE PROGRAMS.


http://www.java2s.com/Tutorial/Java/0040__Data-Type/ThejavautilDateClass.htm
Random
The Random class is a generator of pseudorandom numbers. These are
called pseudorandom numbers because they are simply uniformly
distributed sequences. Random defines the following constructors:
Random( )
Random(long seed)
The first version creates a number generator that uses the current time
as the starting, or seed,value. The second form allows you to specify a
seed value manually.
Class declaration
Following is the declaration for java.util.Random class:
public class Random extends Object implements Serializable
Method Description
boolean nextBoolean( ) Returns the next boolean random number.
void nextBytes(byte vals[ ])Fills vals with randomly generated values.
double nextDouble( ) Returns the next double random number.
float nextFloat( ) Returns the next float random number.
double nextGaussian( ) Returns the next Gaussian random number.
int nextInt( ) Returns the next int random number.
int nextInt(int n) Returns the next int random number
within the range zero to n.
long nextLong( ) Returns the next long random number.
void setSeed(long newSeed) Sets the seed value (that is, the starting
point for the random number generator)
to that specified by newSeed.
import java.util.Random; System.out.println("Average of
class RandDemo { values: " +(sum/100));
public static void main(String // display bell curve, sideways
args[]) { for(int i=0; i<10; i++) {
Random r = new Random(); for(int x=bell[i]; x>0; x--)
double val; System.out.print("*");
double sum = 0; System.out.println();
int bell[] = new int[10]; }}}
for(int i=0; i<100; i++) {
val = r.nextGaussian();
sum += val;
double t = -2;
for(int x=0; x<10; x++, t += 0.5)
if(val < t) {
bell[x]++;
break;
}}
Example:
package javaapps;

public class GeneratingRandomNumbers {


public static void main(String[] args) {
//Generating random numbers within a given number range
//setting min and max number borders
int min = 0; //included
int max = 10; //included
System.out.println(“generating 5 random numbers between ” + min + ” and ” +
max );
for (int i = 0; i < 5; i++) {
System.out.println(“number generated is –> ” + ((int) (Math.random() * (max
– min + 1) ) + min ));
}
min = 50; //included
max = 150; //included
System.out.println(“generating 5 random numbers between ” + min + ” and ” +
max );
for (int i = 0; i < 5; i++) {
System.out.println(“number generated is –> ” + ((int) (Math.random() * (max –
min + 1) ) + min ));
}
}
}
Java.io
• Java I/O
– The java.io package
– Streams, Readers and Writers
• Files
– Working with Files
• URLs
– Working with Internet Resources
Java I/O – The Basics
• Java I/O is based around the concept of a stream
– Ordered sequence of information (bytes) coming from a
source, or going to a ‘sink’
– Simplest stream reads/writes only a single byte, or an
array of bytes at a time
• Designed to be platform-independent
• The stream concept is very generic
– Can be applied to many different types of I/O
– Files, Network, Memory, Processes, etc
Java I/O – The Basics
• The java.io package contains all of the I/O
classes.
– Many classes specialised for particular kinds of stream
operations, e.g. file I/O
• Reading/writing single bytes is quite limited
– So, it includes classes which provide extra functionality
– e.g. buffering, reading numbers and Strings (not bytes),
etc.
• Results in large inheritance hierarchy, with separate
trees for input and output stream classes
Java I/O -- InputStream
Java I/O – InputStreams
Java I/O – Using InputStreams
• Basic pattern for I/O programming is as
follows:
Open a stream
While there’s data to read
Process the data
Close the stream
Java I/O – Using InputStreams
• I/O in Java:
InputStream in = new
FileInputStream(“c:\\temp\\myfile.txt”);
int b = in.read();
//EOF is signalled by read() returning -1
while (b != -1)
{
//do something…
b = in.read();
}
in.close();
Java I/O – Using InputStreams
• But using buffering is more efficient, therefore we
always nest our streams…
InputStream inner = new FileInputStream(“c:\\temp\\myfile.txt”);
InputStream in = new BufferedInputStream(inner);
int b = in.read();
//EOF is signalled by read() returning -1
while (b != -1)
{
//do something…
b = in.read();
}
in.close();
Java I/O – Using InputStreams
• We’ve omitted exception handling in the
previous examples
• Almost all methods on the I/O classes
(including constructors) can throw an
IOException or a subclass.
• Always wrap I/O code in try…catch blocks to
handle errors.
Java I/O – Using InputStreams
InputStream in = null;
try
{
InputStream inner = new
FileInputStream(“c:\\temp\\myfile.txt”);
in = new BufferedInputStream(inner);

//process file
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try { in.close(); } catch (Exception e) {}
}
Java I/O – OutputStream
Java I/O – OutputStreams
Java I/O – Using InputStreams
• Basic pattern for output is as follows:
Open a stream
While there’s data to write
Write the data
Close the stream
Java I/O – Using OutputStreams
• Output in Java:
OutputStream out = new
FileOutputStream(“c:\\temp\\myfile.txt”);
while (…)
{
out.write(…);
}
out.close();
Java I/O – Using OutputStreams
OutputStream out = null;
try
{
OutputStream inner = new
FileOutputStream(“c:\\temp\\myfile.txt”);
out = new BufferedOutputStream(inner);

//write data to the file


} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try { out.close(); } catch (Exception e) {}
}
Java I/O – Reader
Java I/O – Readers
Using Readers
Reader in = null;
try
{
Reader inner = new FileReader(“c:\\temp\\myfile.txt”);
in = new BufferedReader(inner);

//process file
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try { in.close(); } catch (Exception e) {}
}
Java I/O – Writer
Java I/O – Writers
Using Writers
Writer out = null;
try
{
Writer inner = new FileWriter(“c:\\temp\\myfile.txt”);
out = new BufferedWriter(inner);

//write data to the file


} catch (IOException e)
{
e.printStackTrace();
}
finally
{
try { out.close(); } catch (Exception e) {}
}
The File Object
• Java provides access to the file system through the
java.io.File object
– Represents files and directories
• Has methods for working with files and directories
– Making directories, listing directory contents
– renaming and deleting, checking permissions, etc
• Check whether the File corresponds to a directory or
a file with isDirectory()
TreeSet in Java
TreeSet is one of the most important implementations of the SortedSet interface in Java that
uses a Tree for storage. The ordering of the elements is maintained by a set using their natural
ordering whether or not an explicit comparator is provided. This must be consistent with
equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator
provided at set creation time, depending on which constructor is used.

Few important features of TreeSet are as follows:


TreeSet implements the SortedSet interface so duplicate values are not allowed.
Objects in a TreeSet are stored in a sorted and ascending order.
TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
TreeSet does not allow to insert Heterogeneous objects. It will throw classCastException at
Runtime if trying to add hetrogeneous objects.
TreeSet serves as an excellent choice for storing large amounts of sorted information which are
supposed to be accessed quickly because of its faster access and retrieval time.
TreeSet is basically implementation of a self-balancing binary search tree. Therefore
operations like add, remove and search take O(Log n) time. And operations like printing n
elements in sorted order takes O(n) time.
Constructors of TreeSet class:
TreeSet t = new TreeSet();
This will create empty TreeSet object in which elements will get stored in default natural
sorting order.

You might also like