Unit I1
Unit I1
Unit I1
This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
Class Fundamentals
• Classes create objects and objects use methods to communicate
between them.
2
Classes
• A class is a collection of fields
(data) and methods (procedure or Circle
function) that operate on that centre
data. radius
circumference()
• The basic syntax for a class area()
return-type method-name1(arguments)
{ }
return-type method-name2(arguments)
{ }
}
4
Example: A Complex Number Class
• Suppose we want to create and manipulate complex numbers
– a complex number is a value of the form:
a + bi
Addition and Subtraction
8
Implementing State
• An object’s state is contained in instance variables
// State
private double real;
private double imag;
5 + 9i 2 + 7i
real = 5 real = 2
imag = 9 imag = 7
Implementing Behaviour : Constructors
• Constructors are methods that describe the initial state of an object created
of this class.
•In this model, processes or objects can send and receive messages
(signals, functions, complex data structures, or data packets) to other
processes or objects.
•Objects interact by
passing messages to each other
14
Declaring Objects
two-step process
Declare a variable of the class type
complex c1; C1
C1 Complex
C1 Complex
C2 Complex C2
Garbage Collector
Java handles de-allocation automatically using
garbage collection technique.
Java automatically collects garbage
periodically and releases the memory used to
be used in the future.
If any object does not have a reference and
cannot be used in future then that object
becomes a candidate for automatic garbage
collection.
C2
Eg: Complex C2;
17
Accessing Object
• Syntax for accessing variable and methods in
the class
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
21
public static void main(String args[]) Circle Class
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area +"
Circumference ="+circumf);
}
}
output
Radius=5.0 Area=78.5 Circumference =31.400
22
Reading user input
1. Command line argument
2. Scanner class
3. bufferedReader and InputStream Reader class
4. DataInputstream class
5. Console class
23
1.Command line argument
>javac sample.java
>java sample Hello welcome
class sample
{
public static void main( String arg[]) throws Exception
{
System.out.print("The First Argument is: “+ args[0]);
System.out.print("The Second Argument is:“+args[1]);
}
}
output
The First Arument is : HelloThe Second Argument
is :welcome
24
2.Scanner class
import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String s = scan.next();
int i = scan.nextInt();
5.Console class
import java.io.Console;
Console console = System.console();
String s = console.readLine();
int i = Integer.parseInt(console.readLine());
26
METHOD
27
METHOD
• A collection of statements that are grouped together to
perform an operation
• A method definition consists of a method header and a
method body.
• A method has the following syntax
• Parameters
– Act as a placeholder.
– When a method is invoked, a value is passed to
parameter.
– This value is referred to as actual parameter or
argument.
– The parameter list refers to the type, order, and number
of the parameters of a method.
– Parameters are optional; that is,
Methods
A method is a collection of statements that are
grouped together to perform an operation. It has
two parts
1. Define Method
Method header
Method Body
2. Invoke Method
Method name
Local Parameters
Method header
1. Modifier
2. return type
3. method signature-Method signature is the combination of
the method name and the parameter list.
• Method name
• Formal Parameter-The variables defined in the method
header Define a method
method method
public static int max(int num1, int num2) { signature
header
parameter list
Method Body
Method body contains group of statements and with or with out
return value.
A method may return a value.
The returnValueType is the data type of the value the method
returns. If the method does not return a value, the
returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
int result;
return result;
}
Calling Methods
Testing the max method
This program demonstrates calling a method max to return the
largest of the int values
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
34
Trace Method Invocation
i is now 5
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
35
Trace Method Invocation
j is now 2
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
36
Trace Method Invocation
invoke max(i, j)
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
37
Trace Method Invocation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
38
Trace Method Invocation
declare variable result
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
39
Trace Method Invocation
(num1 > num2) is true since num1
is 5 and num2 is 2
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
40
Trace Method Invocation
result is now 5
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
41
Trace Method Invocation
return result, which is 5
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
42
Trace Method Invocation
return max(i, j) and assign the
return value to k
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
43
Trace Method Invocation
Execute the print statement
public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}
44
void Method Example
void show()
{
System.out.println(“hai”);
}
45
• Difference between Parameter and
Argument ?
– Parameter is a variable defined by the
method that receives a value when the
method is called.
– Argument is a value that is passes to a
method when it is invoked
46
Constructor
47
Constructor in Java
Constructor is a special member method which will
be called automatically when you create an object of
any class.
The main purpose of using constructor is to initialize
an object.
Syntax
className()
{
....... .......
}
Advantages of constructors in Java
Sum()
{ a=10; b=20; }
• Constructor should not return any value even void also. Because basic aim is to
another
class Student
{
int roll; float marks; String name;
void show()
{
System.out.println("Roll: "+roll);
System.out.println("Marks: "+marks);
Output
System.out.println("Name: "+name); Roll: 0
} Marks: 0.0
public static void main(String [] args) Name: null
Syntax
class ClassName
{ .......
ClassName(list of parameters)
.......
.......
class Test
{
int a, b;
Test(int n1, int n2)
{ a=n1; b=n2; }
void show()
{
System.out.println("Value of a = "+a);
Output
System.out.println("Value of b = "+b);
Value of a=33
} Value fo b=55
public static void main(String k [])
{
Test t1=new Test(33, 55);
t1.show();
}
}
• Important points Related to Parameterized
Constructor
• Whenever we create an object using parameterized
constructor, it must be define parameterized
constructor otherwise we will get compile time
error.
• Whenever we define the objects with respect to
both parameterized constructor and default
constructor, It must be define both the constructors.
• In any class can have one default constructor and N
number of parameterized constructors.
Constructor Overloading
void show() {
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
Method Constructor
Method can be any user defined Constructor must be class name
name
Method should have return type It should not have any return type
(even void)
Method should be called explicitly It will be called automatically
either with object reference or whenever object is created
class reference
Method is not provided by The java compiler provides a
compiler in any case. default constructor if we do not
have any constructor.
Java Array
• Array is a collection of similar type of elements
that have contiguous memory location.
• Java array is an object the contains elements
of similar data type. It is a data structure
where we store similar elements. We can
store only fixed set of elements in a java array.
• Array in java is index based, first element of
the array is stored at 0 index.
Java Array
Java Array
• Advantage of Java Array
– Code Optimization: It makes the code optimized,
we can retrieve or sort the data easily.
– Random access: We can get any data located at any
index position.
• Disadvantage of Java Array
– Size Limit: We can store only fixed size of elements
in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in
java.
Types of Array
• There are two types of array.
– Single Dimensional Array
– Multidimensional Array
Types of Array in java
Single Dimensional Array in java
Syntax to Declare an Array in java
– dataType[] arr; (or)
– dataType []arr; (or)
– dataType arr[];
Instantiation of an Array in java
– arrayRefVar=new datatype[size];
Types of Array
class Testarray{
public static void main(String args[]){
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Types of Array
int a[]={33,3,4,5};
a[0]=33
a[1]=3
a[2]=4
a[3]=5;
Types of Array
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i]) min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Multidimensional array
Syntax to Declare Multidimensional Array in java
• dataType[][] arrayRefVar; (or)
• dataType [][]arrayRefVar; (or)
• dataType arrayRefVar[][]; (or)
• dataType []arrayRefVar[];
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Copying a java array
• We can copy an array to another by the arraycopy
method of System class.
Syntax of arraycopy method
public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length )
Copying a java array
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
for(int i:arr){
System.out.println(i);
}
}
}
• Excerice
– Create a student class with Name,no and 8 marks.
– Read data from user and calculate average and
class display in to screen
{ System.out.println(a+b); }
89
Access Modifiers in Java
• Default members of the class are accessible only within the same class and
another class of the same package. The default are also called package level
access modifiers.
//save by A.java //save by B.java
package pack; package pack;
class A { Class B{
void show() public static void main(String args[])
{ {
System.out.println("Hello Java"); A obj = new A();
obj.show();
} }
} Output
//save by C.java Hello Java
package pack2;
import pack1.*;
class C
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error, can't access outside the package
obj.show(); //Compile Time Error, can't access outside the package
}
Access Modifiers in Java
Rules for access modifiers:
• The following diagram gives rules for Access
modifiers.
Inheritance
Inheritance
• One of the most effective features of Oop’s
paradigm.
• Establish a link/connectivity between 2 or more
classes.
• Permits sharing and accessing properties from
one to another class.
• SW industry requirement
– Quick,Correct,Economic-
• It apply only it have IS-A relation between classes
Inheritance Motivation
• Inheritance in Java is achieved through
extending classes
Inheritance enables:
• Code re-use
• Grouping similar code
• Flexibility to customize
Inheritance Motivation
PaperBook
PaperBook
ISBN
ISBN
Title
Title
Author
Author
Price
Price
Shipping Price
Stock
Shipping Price
Stock
EBook
EBook
ISBN
ISBN
Title
Title
Author
Author
Price
Price
URL
URL
Size
Size
Inheritance Concepts
• Many real-life objects are related in a hierarchical
fashion such that lower levels of the hierarchy inherit
characteristics of the upper levels.
e.g.,
vehicle car Honda Accord
person employee faculty member
Sub Super
Sub class
• Every object of a class holds one copy of the
instance of the class
• Incase of inheritance , Every object of
inherited object holds not only the copy of
instance of the class also holds all the copy of
instance of all its super classes.
Grand Dad Property -A
Dad Property –B
Son Property –C
Grand Son Property -D
Class B A,B,C
A,B,C
D,E,F,G,H,J,i
X,Y,Z
X,Y,Z
Inheritance Concepts - Hierarchy
• The inheritance hierarchy is
usually drawn as an inverted
(upside-down) tree.
• The tree can have any
number of levels.
• The class at the top (base) of
the inverted tree is called the
root class.
• In Java, the root class is called
Object.
Inheritance Concepts - Hierarchy
Category of Classes on the Basis of
Inheritance
Super class
(base/parentclass).
Child class
(sub/associate/inherited class).
Object Root Class
• The Object root class provides the following
capabilities to all Java objects:
String color;
int speed;
int size;
Expected Output
Display()
Color of Car : Blue
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5
Car
int CC;
int gears;
displaycar()
// A class to display the attributes of the vehicle public class Test
class Vehicle { public static void main(String a[])
{ {
String color; int speed; int size; Car b1 = new Car();
void display() b1.color = "Blue";
{ System.out.println("Color : " + color); b1.speed = 200 ;
System.out.println("Speed : " + speed); b1.size = 22;
System.out.println("Size : " + size); b1.CC = 1000;
} b1.gears = 5; b1.displaycar();
} }
}
C
Constructor Function Calls
class A
{
A() { System.out.println("One"); }
} OUTPUT :
class B extends A One
{ Two
B() { System.out.println("Two"); } Three
}
class C extends B
{
C() {
System.out.println("Three"); }
}
class ConstuctorOrder1
{
public static void main(String args[])
{ C XX= new C(); }
}
Types of inheritance
• Single Inheritance.
• Multiple Inheritance (Through Interface)
• Multilevel Inheritance.
• Hierarchical Inheritance.
• Hybrid Inheritance (Through Interface)
Cant direct implement
with help of interface
Types of inheritance
• Multi-level inheritance is allowed in Java
but not multiple inheritance
The keyword super
class Animal{
Animal void eat(){System.out.println("eating...");}
}
eat()
Output:
eating
Parameterized Constructor using Super
• When an object is created:
– only one constructor function is called
– parameters are passed only to that constructor function
–
Animal Dog
String Name
int age
String Owner
Animal(String,String) Dog()
• But the first two parameters “belong” to the base class (Animal)
constructor function.
• How can those parameters be passed to the Animal constructor
function?
Parameterized Constructor using Super
The keyword super enables parameter passing
between derived and base class constructor
functions
137
Member Override
• When a member of a derived class has the same name
as a member of a base class the derived class member
is said to override the base class member.
(Or )
• If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding in java.
Output:
Vehicle is running
Method overriding
Output:
Bike is running safely
class A
{
void show()
class sample
{
{
System.out.println("Inside A's show");
public static void main(String arg[])
}
{
}
C cc=new C();
class B extends A cc.show();
}
{
}
void show()
{
System.out.println("Inside B's show");
}
}
class C extends B
{
void show()
{
System.out.println("Inside C's show");
}
}
142
class A
{
void show()
class sample
{
{
System.out.println("Inside A's show");
public static void main(String arg[])
}
{
}
C cc=new C();
class B extends A cc.show();
}
{
}
void show()
{
super.show();
System.out.println("Inside B's show");
}
}
class C extends B
{
void show()
{
super.show();
System.out.println("Inside C's show");
}
} 143
class A
{
void show()
{
System.out.println("Inside A's show; No arguments");
}
}
class B extends A
{
void show(String a)
{
System.out.println("Inside B's show; 1 argument "+a);
}
}
class C extends B
{
void show(String a, String b)
{
System.out.println("Inside C's show; 2 arguments "+a+" "+b);
}
144
}
class sample
{
public static void main(String arg[])
{
C cc=new C();
cc.show(); cc.show(“Hello”); cc.show(“Hello”, “World”);
145
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
• This is called as Run-time Polymorphism
146
class A
{
void show() class sample
{ {
System.out.println("Inside A's show"); public static void main(String arg[])
} {
} A aa=new A();
B bb=new B();
class B extends A C cc=new C();
{ A rr;
void show()
{ rr=aa;
System.out.println("Inside B's show"); rr.show();
}
} rr=bb;
rr.show();
class C extends B
{ rr=cc;
void show() rr.show();
{
System.out.println("Inside C's show"); }
} }
}
147
method overloading and method overriding in java
Method Overloading Method Overriding
Method overloading is used to Method overriding is used to provide
increase the readability of the the specific implementation of the
program. method that is already provided by its
super class.
Method overloading is Method overriding occurs in two
performed within class. classes that have IS-A (inheritance)
relationship.
In case of method In case of method
overloading, parameter must be overriding, parameter must be same.
different.
Method overloading is the Method overriding is the example
example of compile time of run time polymorphism.
polymorphism.
In java, method overloading can't Return type must be same or
be performed by changing return covariant in method overriding.
type of the method only. Return
type can be same or different in
method overloading. But you
must have to change the
Difference between method overloading and method overriding in java
Example for
overloading
class OverloadingExample{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class Animal{
void eat(){System.out.println("eating...");}
Example for }
overriding class Dog extends Animal{
void eat()
{System.out.println("eating bread...");}
}