Unit I1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 147

Classes and Objects in Java

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.

• They provide a convenient method for packaging a group of


logically related data items and functions that work on them.

• A class essentially serves as a template for an object and behaves


like a basic data type “int”.

• It is therefore important to understand how the fields and methods


are defined in a class and how they are used to build a Java program
that incorporates the basic OO concepts such as encapsulation,
inheritance, and polymorphism.

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()

definition: class ClassName


{
//State (instance variables)
// Behaviour(instance methods)
// constructors
// accessors
// mutators
// operations/messages 3
}
General Form of a Class
class <class-name>
{
datatype1 var1;
datatype2 var2;

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

Multiplication and division


Classes-Example
public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference()
{
return 2*3.14*r;
}
public double area()
{
return 3.14 * r * r;
}
} 6
Example: A Complex Number Class
• States
– real and imag
• Behaviours
– initialize a new complex number
– mathematical operations (add two complex
numbers, etc.)
– relational operations (equal, not equal, etc.)
– set the values of the real and imaginary parts
– get the values of the real and imaginary parts
Implementing a Complex Number Class in Java
• An overview of a typical Java implementation, contained in the file
Complex.java

public class Complex


{
// State (instance variables)
// Behaviour(instance methods)
// constructors
// accessors
// mutators
// operations/messages
}

8
Implementing State
• An object’s state is contained in instance variables
// State
private double real;
private double imag;

• Each object created from this class will have separate


occurrences of the instance variables

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.

public Complex() Default Constructor


{
real = 0.0; imag = 0.0;
}
• Constructors are invoked only when the object is created. They cannot be
called otherwise.
Complex c1, c2, c3;
c1 = new Complex();

• Constructors initialize the state of an object upon creation.


c1
real = 0
imag = 0
10
Implementing Behaviour : Accessor Methods
• Objects often have methods that return information about
their state called accessors or getters (because the method
name begins with “get”)
• getReal(), getImag() returns the real,imag part of the
Complex object
public double getReal()
{
return real;
}
public double getImag()
{
return imag;
}
11
Implementing Behaviour : Mutator Methods
• Objects often have methods that change aspects of their state
called mutators or setters (because the method name begins
with “set”)
• setReal(),setImag() changes the real,imag part of the
Complex object

public void setReal(double rp)


{
real = rp;
}
public void setImag(double ip)
{
imag = ip;
}
12
Implementing Behaviour :Operations
• Operations or methods used to do some arithmetic or logical
operations between state.
• Class states may or may not change after its execution

• Instead, we define a plus() method as one of the arithmetic


operations supported by the Complex class:

public Complex plus(Complex c)


{
Complex sum = new Complex(real + c.real, imag + c.imag);
return sum;
}
c3 = c1.plus(c2);
Implementing Behaviour : Message Passing
•Message passing is a form of communication between objects,
processes or other resources used in object-oriented programming,

•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

• In Java, "message passing“


is performed by calling methods

14
Declaring Objects
two-step process
Declare a variable of the class type
complex c1; C1

Acquire an actual, physical copy of the object and assign


it to that variable
c1=new Complex();
C1 Complex

Equivalent to, Complex c1=new Complex();


Assigning Object Reference Variables

• Complex C1=new Complex();


• Complex C2;
• C2=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)

Complex c1=new Complex();


c1.real=10; c1.img=5;//Variable
c1.show();//method
18
• Complete Complex class available in current
folder -file Name: complex.java
Example

Write a java program to create


a circle class with x , y and r
data.
And write a method to
calculate Area and
circumference of the circle.
// Circle.java: Contains both Circle class Circle
and itsClass
user
class
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}

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();

3.BufferedReader and InputStreamReader classes


import java.io.BufferedReader;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String s = br.readLine();
int i = Integer.parseInt(br.readLine());
25
4.DataInputStream class
import java.io.DataInputStream;
DataInputStream dis = new
DataInputStream(System.in);
int i = dis.readInt();

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

modifier return_Type Method_Name (list of


parameters)
{
// Method body;
}
• Method Name
– The actual name of the method.
– Method name and the parameter list together
constitute the method signature.

• 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

return value method formal


modifier type name parameters

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.

public static int max(int num1, int num2) {

int result;

if (num1 > num2)


result = num1;
method else
body result = num2;
return value
return result;
}
Invoke Methods
Methods can be invoke by calling the methods
with method name and actual parameters.
Define a method Invoke a method

public static int max(int num1, int num2) {


int z = max(x, y);
int result;
actual parameters
if (num1 > num2) (arguments)
result = num1;
else
result = num2;

return result;
}
Calling Methods
Testing the max method
This program demonstrates calling a method max to return the
largest of the int values

pass the value of i


pass the value of 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;
}

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

This type of method does not return a value. The method


performs some actions.

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

• A constructor eliminates placing the default


values.
• A constructor eliminates calling the normal or
ordinary method implicitly.
How Constructor eliminate default values ?

• Constructor are mainly used for eliminate


default value, whenever you create object of
any class then it allocate memory of variable
and store or initialized default value.
• Using constructor we initialized our own value
in variable.
class Sum Example
{
public int a,b;

Sum()
{ a=10; b=20; }

public static void main(String s[])


{
Output
Sum s=new Sum(); 30
int c= s.a + s.b;
System.out.println("Sum: "+c);
}
Properties of constructor
• Constructor will be called automatically when the object is created.

• Constructor name must be similar to name of the class.

• Constructor should not return any value even void also. Because basic aim is to

place the value in the object

• Constructor definitions should not be static. Because constructors will be called

each and every time, whenever an object is creating.

• Constructor should not be private provided an object of one class is created in

another

• Constructors will not be inherited from one class to another class


There are two types of constructors:
Default Constructor

• A constructor is said to be default constructor if and only


if it never take any parameters.
• If any class does not contain at least one user defined
constructor than the system will create a default
constructor at the time of compilation it is known as
system defined default constructor.
Syntax
class className
{
classname ()
{
block of statements; // Initialization
}
}
class Test
{
int a, b;
Test ()
{
System.out.println("I am from default Constructor...");
a=10; b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
public static void main(String [] args)
{
Test t1=new Test (); Output:
} I am from default Constructor...
} Value of a: 10
Value of b: 20
Important points Related to default constructor
• Whenever we create an object only with default
constructor, defining the default constructor is optional.
• If we are not defining default constructor of a class, then
JVM will call automatically system defined default
constructor.
• If we define, JVM will call user defined default constructor.

Purpose of default constructor?


• Default constructor provides the default values to the
object like 0, 0.0, null etc. depending on their type (for
integer 0, for string null).
Example of default constructor that displays the default values

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

{ Student s1=new Student(); s1.show(); }


}

Explanation: In the above class, we are not creating any constructor so


compiler provides a default constructor. Here 0, 0.0 and null values
are provided by default constructor.
Parameterized constructor

• If any constructor contain list of variable in its signature is known as


parameterized constructor. A parameterized constructor is one which takes some
parameters.

Syntax
class ClassName

{ .......

ClassName(list of parameters)

.......

.......

ClassName objectname=new ClassName(value1, value2,.....);


Example of Parameterized Constructor

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

• Constructor overloading is a technique in Java in which a


class can have any number of constructors that differ in
parameter lists.

• The compiler differentiates these constructors by taking the


number of parameters, and their type.

• In other words whenever same constructor is existing


multiple times in the same class with different number of
parameters or order of parameters or type of parameters is
known as Constructor overloading.

• In general constructor overloading can be used to initialized


same or different objects with different values.
Constructor Overloading
Syntax
class ClassName
{
ClassName() { .......... .......... }
ClassName(datatype1 value1) {.......}
ClassName(datatype1 value1, datatype2 value2) {.......}
ClassName(datatype2 variable2) {.......}
ClassName(datatype2 value2, datatype1 value1)
{.......} ........
}
Example of overloaded constructor
class Test
{
int a, b;
Test () { System.out.println("I am from default Constructor..."); a=1; b=2; }
Test (int x, int y) { System.out.println("I am from double Parameterized Constructor"); a=x; b=y; }
Test (int x) { System.out.println("I am from single Parameterized Constructor"); a=x; b=x; }
Test (Test T) { System.out.println("I am from Object Parameterized Constructor..."); a=T.a; b=T.b; }

void show() {
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}

public static void main (String k [])


{
Test t1=new Test (); t1.show();
Test t2=new Test (10, 20); t2.show();
Test t3=new Test (1000); t3.show();
Test t4=new Test (t1); } t4.show();
}
}
Difference between Method and Constructor

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[]){

int a[]=new int[5];//declaration and instantiation


a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

//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[];

• int[][] arr=new int[3][3];//3 row and 3 column


class Testarray3{
public static void main(String args[]){

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//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];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);


For(i=0;i<=7i++)
System.out.println(copyTo[i]);
}
}
For-each loop (Advanced or Enhanced For
loop):
Advantage of for-each loop:
• It makes the code more readable.
• It elimnates the possibility of programming
errors.
• Syntax
– for(data_type variable : array | collection){}
For-each loop (Advanced or Enhanced For
loop):
class ForEachExample1{
public static void main(String args[]){
int arr[]={12,13,14,44};

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

– student.java file available in current folder.


Method Overloading

• Methods of the same name can be declared in the same class,


as long as they have different sets of parameters (determined
by the number, types and order of the parameters) – this is
called method overloading.

• When an overloaded method is called, the Java compiler


selects the appropriate method by examining the number,
types and order of the arguments in the call.

• Method overloading is commonly used to create several


methods with the same name that perform the same or
similar tasks, but on different types or different numbers of
arguments.
Syntax
class classname
{
Returntype method() {.........}
Returntype method(datatype1 variable1) {.........}
Returntype method(datatype1 variable1, datatype2 variable2) {..}
Returntype method(datatype2 variable2) {.........}
Returntype method(datatype2 variable2, datatype1 variable1) {..}
}
Different ways to overload the method

• There are two ways to overload the method in java


– By changing number of arguments or parameters
– By changing the data type
By changing number of arguments
• In this example, we have created two overloaded methods, first sum method
performs addition of two numbers and second sum method performs addition
of three numbers
class Addition
{
void sum(int a, int b)
Output
{ System.out.println(a+b); } 30
60
void sum(int a, int b, int c)
{ System.out.println(a+b+c); }

public static void main(String args[]) {


Addition obj=new Addition();
obj.sum(10, 20); obj.sum(10, 20, 30);
}
}
By changing the data type
• In this example, we have created two overloaded methods that differs in data
type. The first sum method receives two integer arguments and second sum
method receives two float arguments.
class Addition
{
void sum(int a, int b)
{ System.out.println(a+b); } Output
30
void sum(float a, float b) 31.04

{ System.out.println(a+b); }

public static void main(String args[]) {


Addition obj=new Addition();
obj.sum(10, 20);
obj.sum(10.5, 20.54);
}
}
Can we overload main() method ?
• Yes, We can overload main() method.
• A Java class can have any number of main() methods. But run
the java program, which class should have main() method
with signature as "public static void main(String[] args)”.
• If you do any modification to this signature, compilation will
be successful. But, not run the java program. we will get the
run time error as main method not found.
Access Modifiers

89
Access Modifiers in Java

• Access modifiers are those which are applied


before data members or methods of a class.
These are used to where to access and where
not to access the data members or methods.
In Java programming these are classified into
four types:
– Private
– Default (not a keyword)
– Protected
– Public
Access Modifiers in Java

• Default is not a keyword (like public, private, protected


are keyword)
• If we are not using private, protected and public
keywords, then JVM is by default taking as default
access modifiers.
• Access modifiers are always used for, how to reuse the
features within the package and access the package
between class to class, interface to interface and
interface to a class.
• Access modifiers provide features accessing and
controlling mechanism among the classes and
interfaces.
private

• Private members of class in not accessible anywhere in program


these are only accessible within the class. Private are also called
class level access modifiers
class Hello
{
private int a=20;
private void show() { System.out.println("Hello java"); }
}
public class Demo
{
public static void main(String args[]) {
Hello obj=new Hello();
System.out.println(obj.a); //Compile Time Error, you can't access private
data
obj.show(); //Compile Time Error, you can't access private methods
}
public

• Public members of any class are accessible anywhere in the program


inside the same class and outside of class, within the same package and
outside of the package. Public are also called universal access modifiers.
class Hello
{
public int a=20;
public void show() { System.out.println("Hello java"); }
}
public class Demo
{
public static void main(String args[])
{
Output
Hello obj=new Hello();
20
System.out.println(obj.a);
Hello Java
obj.show();
}
}.
protected

• Protected members of the class are accessible within the same


class and another class of the same package and also accessible in
inherited class of another package. Protected are also called
derived level access modifiers.
public class A {
protected void show()
{
System.out.println("Hello Java");
} Output
} Hello Java
class B extends A {
public static void main(String args[])
{
B obj = new B();
obj.show();
}
}
Default:

• 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

• These types of hierarchies/relationships may be


called IS-A (e.g., a car is-a vehicle).
IS A
• Cylinder is a type of circle
• Book is a type of page
• Horse is a type of vehicle
• Ice is a type of water
• Vapor is a type of water
• Water is a type of Gas
• House fly is a type of bird
• Student is a type of employee
IS A
• Cylinder is a type of circle
• Book is a type of page
• Horse is a type of vehicle
• Ice is a type of water
• Vapor is a type of water
• Water is a type of Gas
• House fly is type of bird
• Student is a type of employee
Size of Super
Super and Sub classes

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

Grand son  A,B,C,D


Son  A,B,C
Dad  A,B
Grand Dad A
Over head
Class A 10 laks/15 laks
A,B,C,D,E
,F,G,H,I,J

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:

– Event handling - synchronizing execution of


multiple executable objects (e.g., a print spooler
and a printer driver)

– Cloning – creating an exact copy of an object

– Finalization – cleaning up when an object is no


longer needed
Inheritance Concepts - Terms
• OOP languages provide specific mechanisms for
defining inheritance relationships between classes.
• Derived (Child) Class - a class that inherits
characteristics of another class.
• Base (Parent) Class - a class from which
characteristics are inherited by one or more other
classes.
• A derived class inherits data and function members
from ALL of its base classes.
Inheritance Concepts - Example
Inheritance - Embedded Objects
 Think of each derived class object as having a base class object
embedded within it.
Java Inheritance Declarations
• No special coding is required to designate a base class, e.g.,
class Employee { … }
• A derived class must specifically declare the base class from
which it is derived

class derived class-name extends baseclass-name


{
//methods and fields
}
Eg: class HourlyEmployee extends Employee { … }
Vehicle

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();
} }
}

// A subclass which extends for vehicle


class Car extends Vehicle
{
int CC; int gears;
void displaycar()
{System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}
protected Members
• protected access members
– Between public and private in protection
– Accessed only by
• Superclass methods
• Subclass methods
• Methods of classes in same package
Inheritance - Constructor Functions
• When an object of a derived class is created,
the constructor functions of the derived class
and all base classes are also called.

– In what order are constructor functions called and


executed?

– How are parameters passed to base class


constructor functions?
Constructor Function Calls
Constructor Function Calls

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

• The super keyword in java is a reference variable


which is used to refer immediate parent class object.
• Whenever you create the instance of subclass, an
instance of parent class is created implicitly which is
referred by super reference variable.
Usage of java super Keyword
– super can be used to refer immediate parent class instance
variable.
– super can be used to invoke immediate parent class
method.
– super() can be used to invoke immediate parent class
constructor.
super is used to refer immediate parent class instance
variable
class Animal{
Animal
String color="white";
color
}

class Dog extends Animal{


Dog
String color="black";
color
void printColor(){
System.out.println(color);//prints color of Dog
}
}
class TestSuper1{
Output:
black
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
super is used to refer immediate parent class instance
variable class Animal{
String color="white";
Animal }
color
class Dog extends Animal{
String color="black";
Dog void printColor(){
color System.out.println(color);//prints color of Dog
System.out.println(super.color);// color of Animal
} }
class TestSuper1{
public static void main(String args[]){
Output: Dog d=new Dog();
black d.printColor();
white
}}
super can be used to invoke parent class method

class Animal{
Animal void eat(){System.out.println("eating...");}
}
eat()

class Dog extends Animal{


void work(){ super.eat(); }
Dog
}
work() class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

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()

• Dog d=new Dog(“Dog”,”XXX”,15);

• 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

For example, the following code passes the first


two parameters from the Dog constructor
function to the Animal constructor function:

public Dog( String N, String O, int a) {


super(N,O);
age=a;
}
Dog d=new Dog(“Dog”,”XXX”,15);
What is difference between super and
super() in Java?
• super with variables and methods: super is used to
call super class variables and methods by the
subclass object when they are overridden by
subclass.
• super() with constructors: super() is used to call
super class constructor from subclass constructor.
Method Overriding
• 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.
– No need of differences in argument type/number

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.

• The derived class member “hides” the base class


member unless a qualified name is used.
• Both the base and derived class implementations of
the overridden data or function member exist within
each derived class object.
Member Override

Usage of Java Method Overriding


• Method overriding is used to provide specific
implementation of a method that is already provided
by its super class.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• method must have same name as in the parent class
• must be IS-A relationship (inheritance).
Method overriding

Vehicle class class Vehicle{


run() void run(){System.out.println("Vehicle is running");} }

public class Bike extends Vehicle{


Bike public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
}

Output:
Vehicle is running
Method overriding

Vehicle class class Vehicle{


run() void run(){System.out.println("Vehicle is running");} }

public class Bike extends Vehicle{


Bike void run(){System.out.println("Bike is running safely");}
run()
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
}
}

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”);

} cc.show(“Hello”, “World”, “Nice”);


}

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...");}
}

You might also like