Second Unit
Second Unit
Class
1. Java is a true object oriented programming language. Anything we wish to represent must
be encapsulated in a class.
2. A class can be defined as a template/blue print that describes behavior/ state of its
objects.
3. Classes packs together a group of logically related data items and functions that operate
on them.
4. Data item are called fields and functions are called methods.
5. Calling specific method is known as sending the object, a message.
Defining a class
Class is a user defined data types with a template that defines its properties.
Similar data type declarations, we can create variables of class type.
These variables are called instances of class or objects.
Syntax:
Field declaration
Data fields are placed inside the body of class definition through variable declarations.
They are created whenever an object instantiated. Hence they are called as instance
variables.
Instance variables are declared the same way as we declared local variables.
Instance variables are also known as member variables.
1
Example
Class Time {
int hours;
int minutes;
int seconds;
}
The class Time contains three integers type instance variables .The declaration can be written in
single line as :
int hours, minutes, seconds;
Methods declarations:
A class with only data field has no life. They can’t respond message.
Methods must beaded to the class to manipulate the data in the class;
Methods are declared inside the body of the class after field declarations.
Instance variables are accessible to the methods
Syntax
type - Type of value it returns. It can be any data type such as int, float etc. It is void, if the
method does not return any value.
parameter-list list of parameter separated by comma. Which are passed to it. Eachparameter
should be given with its data types.
Method body : body of the method in braces {}. Which describes the operations to be
performed on dat.
Example:
Class nu
{int a,b;
void sum()
{ int c;
c=a+b;
System.out.println(c);}
2
int getdata()
{
return a;
}
}
Class Time
{
int hours, minutes, seconds;
int settime(int h; int m; int s)
{
hours=h;
minutes = m;
seconds = s;
}
}
Method set time initializes the data fields hours, minutes and seconds with values h,m and s
passed to it.
class rectangle
{
int length, width;
void setdata (int x, int y)
{
length = x;
width = y;
}
int rectarea()
{
int area;
area = length * width;
return area;
}
}
Set data methods set the values for length and width fields and rectArea method computes area
and return the results.
Creating objects
3
New operator creates an object and return a reference to the object in object variables
Any number of object can be created for a class.
Each object has its own copy of instance variables.
Two or more references can be created for the same object.
Example :
Rectangle r1;
r1 = new rectangle();
Here, variable r1 is an object of rectangle class. The two statement given above can be combined
into one as shown below;
rectangle r2 = r1;
Data members (fields) or function members (methods) of aclass can be accessed using
object name.
All the member should be given value before they are used,
Methods are called with object with name,dot operator, method name and actual values
of its parameters, if any.
Constructors
Java supports a new type of methods, called a constructor. Thar enables an object to initialize
itself when its created.
4
Rules for writing constructor:
Example:
class Rectangle
{
In main() method of another class (RectangleTest) we can declare objects for Rectangle class and
initialize the data members using the constructor.
Class RectangleTest
{
public static void main(String args[])
{
Rectangle r1=new Rectangle(15,20); // constructor is called
int a1;
a1= r1. rectarea();
System.out.println(“Area of Rectangle =” +a1);
}
}
Methods overloading:
Creating more than one method with same name, but different parameters list and
different definition is called overloading.
Method overloading perform similar tasks, but using different parameters
5
Java executes the right methods by matching the parameter list.
This method is known as polymorphism.
Rule:
o The different may be in number of parameters of data type of parameters but not in
return type alone.
o i.e parameter list should be unique.
o Return type does not play any role in overloading.
o Any method can be overloaded including constructor.
Example 1: In this example, add method is overloaded with different types of parameters.
{
int c;
c=a+b;
return c;
}
float add(float a, float b)
{
float c;
c=a+b;
return c;
}
long add(long a, long b)
{
long c;
c=a+b;
return c;
}
Example 2: in this example, line method is overloaded to draw lines of different characters and
length. Number and type of parameters are different.
void line()
{
int i;
c=’-‘;
for(i=1;i<=30;i++)
System.out.print(c);
}
void line(int x)
{
int i;
c=’-‘;
6
for(i=1;i<=x;i++)
System.out.print(c);
}
void line(char c)
{
int i;
for(i=1;i<=30;i++)
System.out.print(c);
}
void line(int x, char c)
{
int i;
for(i=1;i<=x;i++)
System.out.print(c);
}
Calling the function with object O takes the following forms:
Output: -------------------------------------
Output: ---------------------------------------------------------
O.line(*); // which draw a line of 30 *s, Here, the character is passed as parameter
Output: *********************************
O.line(40,’+’); // which draw a line of 40 +s. Here both length and character passed as parameter
Output: +++++++++++++++++++++++++++++++++++++++++
Class Num
{
Int A,B;
Num()
{
A=0;
B=0;
}
Num(int x, int y)
{
A=x;
7
B=y;
}
Num(int x)
{
A=x;
B=x;
}
/* Other methods */
……………
class NumTest
{
public static void main(String args[])
{
Num n1=new Nu0m(); //calls first version of the constructor
Num n2=new Num(5,3); //calls second version of the constructor
Num n3=new Num(9); //calls third version of the constructor
}
}
Static members
Every time a class in instantiated (an object is created) a new copy of all the
members are created.
They are called instance variables and instance methods.
They are accessed using a object with dot operator.
Static members (data and methods )of class are all common to all the objects.
Static data members are declared with static keyword.
They are called as variable and class methods.
They re accessed using class variables and class methods.
They are accessed using class name rather than its object name.
Java creates only one copy of static variables.
Examples:
Rules:
8
Example:
class StaticTest
return x+y;
int sum=StaticTest.add(5,4);
Nesting of methods:
A method is inside class can call another method in the same class. This is known as
nesting of methods.
A call method call another method. i.e method1 can call method2 and method2 in turn
can call method3 and so on.
Example:
class Num
{
inta,b,c;
Num(intx,int y) // constructor
{
a=x;
b=y;
}
void add()
{
c=a+b;
display(); // call to another method in the class
}
void subtract()
{
9
c=a-b;
display(); // call to another method in the class
}
display()
{
System.out.println(a);
System.out.println(b);
System.out.println(“Result=”+c);
}
}
Here the display function is used to display the values of a,b and c. it is called by both add and
subtract methods.
Inheritance:
A A B A
B C B C C C
10
A , B , C and D are Classes
variable declaration;
methods declarations;
The keyword extends states tht the properties of the super classname are extended to the
subclassname.
The subclass will have i9ts own variable and methods and those of the superclass as well.
class Num
{
Int a,b;
Num(int x,int y) // constructor of super class Num
{
a=x;
b=y;
}
void addab()
{
int r;
r=a+b;
System.out.println(r);
}
}
class Numderived extends Num
{
int c;
Numderived(int x,int y, int z)
11
{
Super(x,y); // calls super class constructor with two parameters
c=z;
}
void addabc()
{
int r;
r=a+b+c;
System.out.println(r);
}
}
class SingleInherTest
{
public static void main(String args[])
{
Numderived n1=new Numderived(5,10,15);
n1.addab();
n2.addabc();
}
}
Output:
15
30
Constructor in the derived class Numderived uses the super keyword to pass the values
required for superclass Num constructor.
The object n1 of derived class is able to call the method addab of its super class but due
to inheritance.
It is also calls its own method addabc. It is able to use the variable a and b defined in
super class due to inheritance.
Subclass constructor:
Sub class constructor is used to construct the instance variable of both sub class and
super class. Super keyword invokes the super class constructor.
Rules:
12
o Parameter in super class must match the order and type of the instance variables declared
in super class.
Multilevel inheritance:
A
Grand Father Super class
B
Father Intermediate super class
C
Child Sub class
Hierarchical Inheritance :
Savings
Deposit Current
Long
Short Medium
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.
Method is defined in both superclass and subclass with same name, same arguments,
same return type but different behavior (different code);
13
o Method overriding is used to provode specific implementation of a method that is
already provided by its super class.
o Method overriding is used for runtime polymorphism.
Example:
class Num
{
int a;
Num(int x)
{
a=x;
}
void display()
{
System.out.println(a);
}
}
class Numderived extends Num
{
int b;
Numderived(int x, int y)
{
super(x);
b=y;
}
void display()
{
System.out.println(a);
System.out.println(b);
}
}
The method display() is overridden.
14
Example:
Final class:
Example:
final class a
{
……….
}
Here A can’t be subclassed.
Finalizer Method:
The meaning of abstract is opposite to that of final. Abstract method always must always
be redefined in the subclass. i.e overriding is compulsory.
Classes contain abstract methods should be declared as abstract classes.
Abstract classes should contain abstract methods should be declared as abstract classes.
Abstract class should containabstract methods with prototype without body(code).
Example:
15
abstract class shape
{
…..
…..
abstract void area();
…..
}
class Circle extends shape
{
float radius;
void area()
{
float a;
a = 3.14* radius * radius;
System.out.println(a);
}
}
Rules:
Abstract classes cannot be instantiated i.e. we should not declare objects for abstract
classes .
Abstracts methods of abstract classes must be defined in subclass.
Abstract constructor or abstract static members cannot be defined.
In the example given above, the method area() is not defined in abstract class Shape. It is
defined in sub class Circle.
Visibility Modifiers:
All the members of a class are inherited by sub class, by default.
Access can be restricted using visibility modifiers or access modifiers.
Java provides three types of visibility modifiers: public, private and protected.
Public Access
They are made visible outside the class by declaring them public.
Variables or method declared as public is accessible everywhere in the java program.
It is the widest possible visibility.
16
{
………
………
}
Friendly Access
When no access modifier is specified, the member defaults to a limited version of public
accessibility known as Friendly Access.
Friendly access means the members are visible to all the classes in the package to which
it belongs.
Public access means the members are visible to all the classes in any package.
A package is nothing but source code file in which the class is defined.
Protected Access
Visibility level of protected access lies in between public and friendly access
Protected modifier makes the members visible to all its subclasses in current package as
well as in all the packages.
Non-sub classes can’t access the protected members.
Private Access
A field can be declared with two keywords private and protected together.
Rules of Thumb
Array
An array is a group of homogeneous, data items stored in contiguous locations that share
a common name
For example, an array of total marks obtained by students in an examination
A particular students total mark is referred by writing a number called index or subscript
in square brackets after the array name.
Number [0]
Number [1]
Number [2]
Number [3]
Number [4]
Number[0] = 20; number[1] =12; number[2] =8; number[3]=4; number[5]=15; which are
assigned to locations of the array as shown below:
18
20
12
8
4
15
The elements of an array can be used in Java programs like any other variables.
if(number[1]>big)
big= number[1];
Creating an Array
Array Declaration
Example:
Creation in Memory
19
arrayname= new type[size];
Example:
Here number is an array having 5 locations to store integers. average is an array to store 10
floating point numbers (real).
The two steps, declaration and memory creation can be combijed into one as shown below:
All the locations in an array can be initialized with values at the time of declaration:
The number of values in the list determines the size of the array.
for(i=0;i<100;i++)
Array Length: Java stores the length of an array in a variable length. We can get the size of the
array as.
size = number.length;
20
Two Dimensional Arrays are needed to store a table of values. Two subscripts are used to refer
to a value table, namely row subscript and column subscript.
For example, the following table of values store Day-wise sales of 3 items in a departmental
store:
The table contains 9 values arranged in 3 rows and 3 columns. It can be though of as a matrix of
3 rows and 3 columns. In mathematics, two subscripts are used to refer to a value in a matrix as
in Vij. Where i represents row subscripts and j represents column subscripts.
Two dimensional array for the above example is declared in Java as:
21
Each row containing values for 3 columns are given in separate braces. Comma is required after
each row.
Two dimensional array can also be initialized using nested for loops.
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
v[i][j] = 0;
}
}
Here, all the elements of the array v are initialized to zero values.
Java multidimensional arrays as “array of arrays.It is possible to create different number of columns for
each rowin a dimensional array as shown below.
Array Examples
Sorting Numbers :
importjava.io;
class sortnum
{
Public static void main(String args[])throwsIoException
{
DataInputStream ds = new DataInputStream(System.in);
System.out,printlnI(“Enter the size array”);
Int n= Integer.parseInt(ds.readLine());
Int t;
int a[]=new int[n];
System.out.println(n);
System.out.println(“Enter the elements of array”);
For(int i=0; i<n;i++)
22
{
For(int j=i+1; j<n;j++)
{
If (a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
System.out.println(“Bubble Sort”);
For(int i=0; i<n;i++)
System.out.println(a[i]);
}
}
Matrix Multiplication :
// Multiplying two matrices
import java.io.*;
class matmul
{
public static void main(String args[]) throws IOException
{
DataInputStream ds= new DataInputStream(System.in);
inti,j,k;
String s;
int a[][]=new int[2][2];
int b[][]=new int[2][2];
int c[][]=new int[2][2];
// input loop for matrix a
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.println(“Enter the number of matrix a”);
s=ds.readLine();
a[i][j] = Integer.parseInt(s);
}
}
// input loop for matrix b
for(i=0;i<2;i++)
23
{
for(j=0;j<2;j++)
{
System.out.println(“Enter the number of matrix b”);
s=ds.readLine();
b[i][j] = Integer.parseInt(s);
}
}
// Initialize c matrix with 0
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
c[i][j] = 0;
}
}
//Multiply
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
c[i][j] +=a[i][k]* b[k][j];
}
}
}
//output
System.out.println(“Result of Multiplication”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
System.out.print(c[i][j]+” “);
}
System.out.print(“\n “);
}
}
24
Strings:
string variablename;
length()“”function in string object returns the number of character stored in the string,
string name=(mary);
int x = name.length();
string s1 = “my”;
string s2 = “dog”;
string = s3 = s1 + s2;
String Array :
String array can be created to store more than one string in a single variable name like numerical
arrays.
Example:
import java.io.*;
class alphabetize
{
public static void main(String args[]) throws IOException
{
String n[]=new String[5];
String t;
25
DataInputStream d= new DataInputStream(System.in)
iIntp,c;
//Input loop
for(p=0;p<5;p++)
{
System.out.println(“Enter a Name”);
n[p] =d.readLine();
}
// Bubble Sorting Procedure
for(p=0;p<4;p++)
{
for(c=0;c<4;c++)
{
if (n[c].compareTo(n[c+1])>0)
{
t=n[c];
n[c]=n[c+1];
n[c+1]=t;
}
}
}
//Output loop
for(p=0;p<5;p++)
{
System.out.println(n[p]);
}
}
}
Input: MARY RAM ARUN BALU ILANGO
Output: ARUN BALU ILANGO MARY RAM
String methods:
26
lower case.
s2=s1.toUpperCase(); Converts the string s1 to all S1 = “abc” , s2 = “ABC”
upper case
s2=s1.replace(c1,c2); Replace all ppearances of S1 = “aabbaaccaadd”
character c1 with c2 in s1 S1.replace(‘a’, ‘z’) returns the
string “zzbbzzcczzdd”
s2=s1.trim(); Removes white spaces at the S1 = “ABC ”, s2 =”ABC”
beginning and end of the
string s1.
s1.equals(s2) Returns true if s1= s2 S1= “abcd”, s2 =abcd”
Returns true
S1 = “ABCD”, s2 = “abcd”
returns false
S1.equalsIgnoreCase(s2); Returns true if s1= s2 ignoring S1 = “abcd”, s2 = “abcd”
the casre of letters returns the S1 = “ABCD”, s2 =
“abcd” returns true
S1.length(); Give the nth length of s1 S1 = “abcd” return 4 as length
27
String Buffer strings of flexible length
Strings are mutable. i.e String Buffer strings can be modified in content and length
Characters can be inserted or replaced in the middle of the string.
The following table shows frequently used methods of String Buffer class
Vectors :
Even if the size of specified, any number of objects can be put into a vector(growable).
Vector cant store primitive data types int, float, long, char and double.
28
Vector can store object types only.
Primitive datatypes are to be objects using wrapper classes.
Vector class supports a number of methods to manipulate vectors. Importantones are listed in the
table given below
Method Purpose
list.addElement(item) Adds the specified item at the end of the list.
Or list is avector
list.add(item)
list.elementAt(n) Gives the name of nth element in the list
Or
list.get(n)
list.size() Give the number of objects in the list
list.removeElement(item) Removes the specified item from the list
or
list.remove(item)
list.removeElement(n) Removes the item stored in nth position of list
or
list.remove(n)
Example 1:
import java.util.*;
//ADDing and displaying elements in avector
Public class vector1
{
Public static void main(string[]args)
//create a vector object
Vector v = new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);
//getting elements
System.out.println(“Elements in vector v”);
System.out.println(v.elementAt(0));
System.out.println(v.elementAt(1));
System.out.println(v.elementAt(2));
}
}
Output:
29
Elements in vector v
1
3
5
Example 2:
import java.util.*;
//Inserting an element before a location
public class vector2
{
public static void main(string[]args)
//create vector object
Vector v= new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);
//insert a element in specific location
v.insertElementAt(“2”,1) ;
System.out.println(“Elements in vector after insertion at location 1”)
int I;
for(i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}
}
Output :
2 Inserted Element
Example 3 :
import java.util.*;
//Removing an element at a time
30
public static void main(string[]args)
//create vector object
Vector v= new Vector;
//adding elements
v.addElements(“1”);
v.addElements(“3”);
v.addElements(“5”);
31
After replacing an element
9 Replacing Element
Example 5:
import java.util.*;
int s= v.size;
String varray[] – new String[s]; //declare an array of size s
v.copy.Into(varray);
System.out.println(“Displaying arrayelements”);
int i;
for(i=0;i<s;i++)
System.out.printlm(varray[i]);
//Removing all the elements from vector
v.removeAllElements();
Systemout.println(v.size()); //displays size as zero
}
}
Output:
Displaying array elements
1
3
32
4
Wrapper class:
Wrapper class in java provides the mechanism to convert primitive into object type and
object into primitive type.
The manufacturer wraps the chocolate with some foil or paper to prevent it from
pollution. The user takes the chocolate, removes throws and the wrapper, and ease it.
The following table shows primitive data types and their corresponding wrapper classes.
Primitive data types are converted into objecctr types by calling constructor of wrapper
classes. Object types are converted back into primitive data types using methods in wrapper
classes.
33
Double c= 0.123456789123; C=D.doubleValue();
Double D = new Double(c);
Primitive boolean to Boolean object Boolean object to primitive boolean
Boolean b1 = true; b1 = B1.booleanValue();
Boolean B1 = new Boolean(b1);
String str;
Str = Long.tostring(I);
Float = Float.tostring(f);
Str = Double.valueOf(d);
i=Integer.valueOf(str);
l=Long..valueOf(str);
f=float.valueOf(str);
d=Double.valueOf(str);
i=Integer.parseInt(str)
l=Long.parseLong(str);
Enumerated types:
A enum type is a special data type that enables a variable to be a set of predefined
constants.
The variable must be equal to one of the values that have been predefined for it.
34
Common examples include compass directions (vlue of NOPRTH, SOUTH, EAST,
WEST) and the days of the week.
Because they are constants, the names of an enum types fields are in upper case
letters.
J2SE 5.0 supports enumerated type using enumkeyword.This is similar static final constants in a
earlier versions of java, as shoen as below.
The same coding canbe written using enum type as shown below:
enum Days
Interfaces
35
Interface can contain abstract methods and final fields. Along with abstract
methods and constants n interface may also contain default methods, static methods,
and nested types. Method bodies exist only for default methods and static methods.
It is the responsibility of the classes that implements the interface to defines the code
for implementation of these methods.
Interface fields are public, static and finally by default(so, use the keyword static and
final are optional). Methods are abstract methods with no body(code) defined.
Default interface:
Syntax:
interface InterfaceName
Variable declaration;
Methods declarations;
Here, interface is a keyword and InterfaceName is any valid java variable name.
All variables are declared as constants with keywords static final as shown below:
36
Example:
interfaceArea
void show();
Implement Interface:
Syntax:
Body of classame
37
Class classname extends superclass implements interface1, interface2,……
BODY OF CLASSNAME
Example :
interface area
return(x*y);
return(pi*x*y);
38
}
float result;
System.out.println(“Area of Rectangle=”+result);
System.out.println(“Area of circle=”+result);
Output:
Explanation:
The program given above creates an interface called re, which contains a constant pi and
abstract method compute.
The interface Area is implemented by two classes Rectangle and circle.
Reference variable a for interface Area is created(Note that an objectis not instantiated)
Object r and c for class Rectangle and Circle classes respectively are created.
39
Object reference r and c are stored in a(interface reference variable) and the compute the
method is called
Call to compute method rectangle is called when rectangle objects reference is stored in
interface reference variable.
Call to compute method circle is called when circle objects reference is stored in
interface reference variable.
Extending Interfaces
For example, we can put all the constants in one interface and methods in the other. This will
enable to use constants in classes where the methods are not required.,
Example 1:
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface ItemMethods
{
Void display();
}
class Sales implements ItemConstants
{
……………..
}
class Invoice implements ItemConstant, ItemMethods
‘’’’’’’’’’’’’’
Example 2:
…………….
Interface Item
Class sales
Example3:
Accesinginterface VARIABLES:
Interface can be used to declare set of constants that can be used by different classes.
This similar to creating a header file constants in C and C++.
These constant values will be available to any class that implements that interface.
Interface Constants
{
Int rows = 10;\
Int cols=10;
Float pi=3.14F;
41
Float da_rate = 0.57F;
}
Int r= rows;
Int c=cols;
Float DA;
IntBasic_pay = 5000;
DA = Basic_pay * da_rate;
Float AREA;
Area = pi*radius*radius;
The four constants defined in Constants Interface are available to Matrix Class.
Packages are janamesva’s way of grouping a variety of classes and / or interface together.
Grouping isa done according to functionality
Package are equivalent to class libraries in other languages.
A package canbe defined as a grouping of related types (classes, interfaces, enumeratins
etc..,) providing access protection and name space management.
Programmers can define their own packages to bundle group of classes/Interfaces, etc
It is a good practice to group related classes implemented by you.
Since the package creates a new namespace there won’t be any name conflict with name
in other packages.
Using packages, it is easier to provide access control and it is also easier to locate related
classes.
Programmers can define their own packages to bundle a group of classes/interfaces, etc.
42
It is a good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, and annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages.
Using packages, it is easier to provide access control
It is also easier to locate the related classes.
Package in java are of two types:
1. Java API Package
2. User defined package
Java Api can be used for designing user Interface.
User defined packages can be used for handling our classes.
Java API package a large number of classes grouped in to different packages according to
functionality. The figures shows the functional breakdown of API Paackage.
JAVA
43
Java Packages are organized in a hierarchical structure as shown below:
Java
awt
color
Graphics
font
………..
44
45