Unit 2: Classes, Inheritance, Packages & Interfaces
Unit 2: Classes, Inheritance, Packages & Interfaces
• 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
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.
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.
new keyword
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);
} }
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);
}
} }
//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();
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)
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
}
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;
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
//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)
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;
class Student
package pack1;
public class Student
{
// class body
}
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();
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
.
• 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)
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);
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);
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);
import java.util.Date;
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
//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);
//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);