Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views35 pages

OOP Using JAVA Unit-II

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on arrays, command line arguments, strings, classes, and objects. It explains the creation and manipulation of one-dimensional and two-dimensional arrays, as well as string operations and methods. Additionally, it covers class definitions, object creation, and the significance of encapsulation in OOP.

Uploaded by

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

OOP Using JAVA Unit-II

This document provides an overview of Object-Oriented Programming (OOP) concepts in Java, focusing on arrays, command line arguments, strings, classes, and objects. It explains the creation and manipulation of one-dimensional and two-dimensional arrays, as well as string operations and methods. Additionally, it covers class definitions, object creation, and the significance of encapsulation in OOP.

Uploaded by

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

OOP using JAVA

UNIT-II
Arrays, Command Line Arguments, Strings-String Class Methods
Classes & Objects: Creating Classes, declaring objects, Methods, parameter
passing, static fields and methods, Constructors, and ‘this’ keyword, overloading
methods and access
Inheritance: Inheritance hierarchies, super and subclasses, member access rules,
‘super’ keyword, preventing inheritance: final classes and methods, the object class
and its methods;
Polymorphism: Dynamic binding, method overriding, abstract classes and
methods;

Arrays
Definition
• An array is a collection of same type variables referenced by a common
name.
• All the elements in the array are of the same data type.
• Elements of an array are accessed individually using the index.
• The index value in every array starts with 0 (zero).
• An array can have one or more dimensions
One Dimensional Array
A list of items can be given one variable name using only one subscript
and such a variable is called a single-dimensional variable or a one-dimensional
array.
Creating an array
Creation of arrays is a two step process:
1) Declaring an array variable.
2) Allocating memory for the array.
Declaration of arrays
Syntax for declaring an array variable is:
type array-name[];
Here, type – Data type of the array and array-name is any valid identifier.
We can also declare an array in java as follows,
Type[] array-name;
Examples: int number[];

1
OOP using JAVA

float average[];
int[] counter;
Creation of arrays (Allocating the memory for an array)
After declaring an array, we need to create it in memory. Java allows us to
create arrays using new operator only.
Syntax for allocating memory for an array:
array-name = new type[size];
Here, new – keyword used to allocate memory for the array, and
size – No of elements that the array will hold.
We can combine both the steps into a single one as shown below:
type array-name[] = new type[size];
Examples:
number=new int[5];
average=new float[10];
The following figure illustrates the creation of an array in memory.

Initialization of Arrays
 Every array element is accessed using its index value.
 Syntax for initializing the array elements is:
array-name[index] = value;
Example:
int a[] = new int[3];
a[0] = 10;

2
OOP using JAVA

a[1] = 20;
a[2] = 30;
 There is another way for initializing array elements, right at the time of
declaring the array.
Example:
int a[] = {1,2,3,4,5};
In the above example, ‘a’ is an integer type array with size automatically
set to 5. All the 5 elements are initialized with the values 1,2,3,4,5.
a[0] is 1, a[1] is 2, a[2] is 3, a[3] is 4 and a[4] is 5.
Array Length
In java, all arrays store the allocated size in a variable named length. We
can obtain the length of the array using the length.
Example:
int number[]={10,20,30,40,50};
int n=number.length;
The following java program illustrates the concept of single dimensional arrays.
Aim: To sort an array of elements
Program:
//ArrayDemo.java
import java.io.*;
class ArrayDemo
{
public static void main(String[] args) throws IOException
{
int a[];
int n,temp;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the array size.....");
n=Integer.parseInt(in.readLine());
a=new int[n];
System.out.println("Enter the elements into the array");
for(int i=0;i<n;i++)

3
OOP using JAVA

{
a[i]=Integer.parseInt(in.readLine());
}
System.out.println("The array elements before Sorting are....");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
System.out.println("The array elements after Sorting are.....");
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>=a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}

4
OOP using JAVA

Output

Two-Dimensional Arrays
 Until now we have only seen one-dimensional array. But, an array in
general can have more than one dimension.
 Let’s see about two-dimensional arrays. For each dimension, we must
specify an extra set of [].
A two dimensional array is declared as shown below:
int a[][] = new int[3][4];
‘a’ is a two dimensional array which can hold 12 elements in 3 rows
and 4 columns.
 Initializing two dimensional array elements is done using the index values:
int a[][] = new int[2][2];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
The following is a representation of a two-dimensional array in memory.

5
OOP using JAVA

• We can directly initialize the elements of a two dimensional array as shown


below:
int a[][] = { {1,2},{3,4}};
• Alternative way of declaring a two dimensional array is:
int[][] a = {{1,2},{3,4}};
The following program illustrates the concept of two-dimensional arrays in java.
Aim: To read and print a matrix.
Program:
//ArrayDemo1.java
import java.io.*;
class ArrayDemo1
{
public static void main(String[] args) throws IOException
{
int a[][];
int m,n;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the number of rows of a matrix.....");
m=Integer.parseInt(in.readLine());
System.out.println("Enter the number of Columns of a matrix.....");
n=Integer.parseInt(in.readLine());
a=new int[m][n];
System.out.println("Enter the elements into the matrix....");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(in.readLine());
}
}
System.out.println("The matrix elements are....");
for(int i=0;i<n;i++)
6
OOP using JAVA

{
for(int j=0;j<n;j++)
{
System.out.print(" " + a[i][j]);
}
System.out.println("\n");
}
}//main()
}//ArrayDemo1
Output

Variable Size Arrays


Java treats multidimensional arrays as “arrays of arrays”. It is possible to
declare a two-dimensional array as follows.
int x[][[]=new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
These statements create a two-dimensional array as having different
lengths for each row as shown in below.

7
OOP using JAVA

****************************************************************
Command Line Arguments
In java command-line argument is an argument i.e. passed at the time of
running the java program.
The arguments passed from the console can be received in the java program
and it can be used as an input. So, it provides a convenient way to check the
behaviour of the program for the different values. We can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
Example:
class Commandline
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("No.of Arguments="+count);
while(i<count)
{
str=args[i];
i=i+1;
System.out.println(i+":"+"Java is "+str);
}
}
}
Output:

****************************************************************
Strings
• A string is a sequence/group of characters.
• Strings in java are implemented as objects of the class “String” unlike other
languages which implement strings using character arrays.
• Once a string (object) is created, we cannot change the characters in that
string. Rather, we can create a new string object.

8
OOP using JAVA

• All kind of string operations like concatenation, copying, case inversion


and substring and many others can be performed on string objects.
• In java, Strings are class objects and implemented using two classes,
namely, String and StringBuffer.
• A java String is not a character array and is not NULL terminated.

Strings may be declared and created as follows:


String stringname= new String(“string”);
Example:
String name=new String(“kanth”); //is same as
String name=”kanth”;
Like arrays, it is possible to get the length of string using the length method of
the String class.
int len = name.length();
Java string can be concatenated using the + operator.
E.g.: String firstname = “sri”;
String lastname = “kanth”;
String name = firstname+lastname;
( or ) String name = “sri”+”kanth”;

String Arrays:
We can also create and use arrays that contain strings. The statement,
String names[]=new String[3];
will create an names array of size 3 to hold three string constants

String Methods: (Methods of String class)


The String class defines a number of methods that allow us to accomplish
a variety of string manipulation tasks.
Method Task
s2=s1.toLowerCase() converts the String s1 to all lowecase
s2=s1.toUpperCase() converts the String s1 to all Uppercase
s2=s1.replace(‗x‘,‘y‘); Replace all appearances of x with y

9
OOP using JAVA

s2=s1.trim(); Remove white spaces at the beginning and


end of String s1
s1.equals(s2); Returns ‗true‘ if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns ‗true‘ if s1=s2, ignoring the case
of characters
s1.length() Gives the length of s1
s1.CharAt(n) Gives nth character of s1
s1.compareTo(s2) Returns –ve if s1<s2, +ve if s1>s2, and 0
if s1 is equal s2
s1.concat(s2) Concatenates s1 and s2
s1.indexOf(‗x‘) Gives the position of the first occurrence
of ‗x‘ in string s1
s1.indexOf(‗x‘,n) Gives the position of ‗x‘ that occurs after
nth position in the string s1
The following program illustrates the concept of String class in java
Aim: To sort the string in Alphabetical order
Program:
//StringOrdering.java
//Alphabetical ordering of strings
class StringOrdering
{
public static void main(String args[])
{
String names[]={"india","usa","australia","africa","japan"};
int size=names.length;
String temp;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(names[j].compareTo(names[i])<0)
{
temp=names[i];
names[i]=names[j];
names[j]=temp;
}
}
}
10
OOP using JAVA

for(int i=0;i<size;i++)
System.out.println(names[i]);
}
}
Output:

StringBuffer Class :
StringBuffer is a peer class of String. While String creates string of fixed
length, StringBuffer creates strings of flexible length that can be modified in
terms of both length and content. We can insert characters and substrings in the
middle of a string, or append another string to the end. Below, there are some of
methods that are frequently used in string manipulations.

Method Task
s1.setCharAt(n,‘x‘) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n,s2) Inserts the string s2 at the position n of the
string s1
s1.setLength(n) Sets the length of the string s1 to n. If
n<s1.length() s1 is truncated .if
n>s1.length() zeros are added to s1

The following program illustrates the concept of StringBuffer class in java.


Program:
class StringBufferConst
{
public static void main(String args[])
{
StringBuffer buff1 = new StringBuffer();
System.out.println("Length is: "+buff1.length());
System.out.println("Capacity is: "+buff1.capacity());

11
OOP using JAVA

StringBuffer buff2 = new StringBuffer(20);


System.out.println("Length is: "+buff2.length());
System.out.println("Capacity is: "+buff2.capacity());

StringBuffer buff3 = new StringBuffer("hello");


System.out.println("Length is: "+buff3.length());
System.out.println("Capacity is: "+buff3.capacity());

CharSequence seq = "Hai";


StringBuffer buff4 = new StringBuffer(seq);
System.out.println("Length is: "+buff4.length());
System.out.println("Capacity is: "+buff4.capacity());
}
}
Output:

****************************************************************
Classes and Objects
Defining a Class
Definition:
The process of binding the data members and member functions into a
single unit is called as a class. In other words a class is a user defined data type.
Once the class type has been defined, we can create “variables” of that type. In
java these variables are termed as instances of classes, which are the actual
objects.
The basic form of a class definition is as follows
class clsname [ extends superclsname]
{
[fields declaration];
[methods declaration];

12
OOP using JAVA

}
Here, clasname and superclsname are any valid java identifiers. The
keyword extends indicates that the properties of the superclsname class are
extended to the clsname class. This concept is called as inheritance.
Everything inside the square brackets is optional. This means that the
following would be a valid class definition.
class clsname
{
}
Here, the body of the class is empty, this does not contain any properties
and therefore cannot do anything.
Fields Declaration
Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables because they are
created whenever an object of the class is instantiated. Instance variables are also
known as member variables. We can declare the instance variables exactly the
same way as we declare the local variables.
Example:
class Rectangle
{
int length;
int width;
}
The class Rectangle contains two integer type instance variables. Here,
these variables are only declared and therefore no storage space has been created
in the memory.
Methods Declaration
A class with only data fields has no life. The objects created by such a class
cannot respond to any messages.
Methods are declared inside the body of the class but immediately after the
declaration of instance variables. The general form of a method declaration is as
follows.
type methodname ( parameter_list)
{
Method-body;
}

13
OOP using JAVA

Method declaration have four basic parts:


 The name of the method (methodname).
 The type of the value the method returns (type).
 A list of parameters (parameter_list)
 The body of the method.
Let us consider a Rectangle class example as follows
class Rectangle
{
int length;
int width;
void getData( int x, int y) // Method declaration
{
length=x;
width=y;
}
}

Creating Objects
An instance of a class is called as an object. An object in java is essentially
a block of memory that contains space to store all the member variables. Crating
an object is also referred to as instantiating an object.
Objects in java are created using the new operator. The new operator
creates an object of the specified class and returns a reference to that object.
Here is an example of creating an object of type Rectangle.
Rectangle o1; //declaring the object
o1=new Rectangle(); // instantiate the object
The first statement declares a variable to hold the object reference and the
second one actually assigns the object reference to the variable. The variable o1
is now an object of the Rectangle class.
Both statements can be combined into one as shown below.
Rectangle o1=new Rectangle();
The method Rectangle ( ) is the default constructor of the class. We can
create any number of objects of Rectangle. For example
Rectangle o1= new Rectangle();
Rectangle o2= new Rectangle();

14
OOP using JAVA

It is important to understand that each object has its own copy of the
instance variable of its class. This means that any changes to the variables of one
object can have no effect on the variables of another.
It is also possible to create two or more references to the same object as
shown in below.
Rectangle R1=new Rectangle ();
Rectangle R2=R1;

Accessing class members


To access the instance variables and the methods of a class we must use
the concerned object and the dot ( . ) operator as shown in below.
objname.variablename=value;
objname.methodname(parameter_list);
Here, objname is the name of the objet and variablename is the name of
the instance variable inside the object that we wish to access.
The following is the program that illustrates the concepts discussed so far.
Aim: To find the area of a rectangle.
Program
//RectArea.java
class Rectangle
{
int len,wid; // Declaration of variables
void getData(int x, int y) //Declaration of method
{
len=x;
wid=y;
}
int rectArea() //Definition of another method
{
int area=len*wid;
return (area);
}
}
class RectArea // class with main method
{
public static void main(String args[])

15
OOP using JAVA

{
int area1, area2;
Rectangle r1=new Rectangle(); // Creating objects
Rectangle r2=new Rectangle();

r1.len=15; //Accessing Variables


r1.wid=10;

area1=r1.len * r1.wid;

r2.getData(20,12); //Accessing methods


area2=r2.rectArea();

System.out.println("Area1=" + area1);
System.out.println("Area2=" + area2);
}
}
Output:

****************************************************************
Access Specifiers:
In Java, the access specifiers (also known as access modifiers) used to
restrict the scope or accessibility of a class, constructor, variable, method or
data member of class and interface. There are four access specifiers, and their
list is below.
 default (or) no modifiers

 public

 protected

 private

16
OOP using JAVA

An access specifier is a keyword that specifies how to access-the members


of a class or a class itself. We can use access specifiers before a class and its
members: There are four access specifiers available in Java:
 private: 'private' members of a-class are not accessible anywhere outside
the class. They are accessible only within the class by the methods of that
class.
 public: 'public' members of a class are accessible everywhere outside the
class. So any other program can read them and use them.
 protected: 'protected' members of a class are accessible outside the class,
but generally, within the same directory.
 default: If no access specifier is written by the programmer, then the Java
compiler uses a 'default' access specifier. 'default' members are accessible
outside the class, but within' the same directory.

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

****************************************************************

Static Fields & Methods in Java.


static variable:
 It is a variable which belongs to the class and not to object(instance).
 Static variables are initialized only once, at the start of the execution.
These variables

will be initialized first, before the initialization of any instance variables.

17
OOP using JAVA

 A single copy to be shared by all instances of the class.


 A static variable can be accessed directly by the class name and doesn’t
need any object.

The following is the syntax for accessing a static variable


Syntax
<class-name>.<variable-name>

static method:
 It is a method which belongs to the class and not to the object(instance).
 A static method can access only static data. It cannot access non-static data
(instance variables).
 A static method can call only other static methods and cannot call a non-
static method from it.
 A static method can be accessed directly by the class name and doesn’t
need any object.

The following is the syntax for accessing a static variable


Syntax:<class-name>.<method-name>
Program:
class Test
{
static int x=55;
static void access()
{
System.out.println(“x=”+x);
}
}
class Demo
{
public static void main(String args[])
{
Test.access();
}
}

18
OOP using JAVA

Output:

Static Block:
A static block is a block of statements declared as 'static', something like
this
static
{
statements;
}
JVM executes a static block on a highest priority basis. This means JVM
first goes to a static block even before it looks for the main( ) method in the
program.
Program:
class Demo
{
static
{
System.out.println("Static block");
}
public static void main(String args[ ])
{
System.out.println("Static method");
}
}
Output:

19
OOP using JAVA

Q) Is it possible to compile and run a Java program without writing main ()


method?
Yes, it is possible by using a static block in the Java program.
Program:
class Demo
{
Static
{
System.out.println(“Static block”);
System.exit(0);
}
}
Output:

****************************************************************
Constructors in Java.
Constructor:
Constructors are special methods having the same name as the class itself.
They do not have a return type, not even void.
A Constructor initializes an object automatically when the object is
created. Constructors can be overloaded like methods. The constructor is
automatically called when an object is created.
Java does three operations when new is used to create an instance of a class.
 Allocates the memory for the object.
 Initializes that objects instance variables, either to initial values or to a
default.
 Calls the constructor of the class.
Constructors look a lot like regular methods with two basic differences.
 Constructors always have the same name as that of class.
 Constructor does not have a return type ( even void)
The following program illustrates the concept of constructors in java.

20
OOP using JAVA

Aim: To find the area of a rectangle.


Program
//Rectangle.java
class Rectangle
{
int len;
int wid;
Rectangle(int x, int y)
{
len=x;
wid=y;
}
int area()
{
return (len*wid);
}
public static void main(String[] args)
{
//Constructor is implicitly called when we create an object
Rectangle r1=new Rectangle(10,20); //calling constructor
int x=r1.area(); //calling the method
System.out.println("Area=" + x);
}
}
Output:

Method Overloading
In java, it is possible to create methods that have the same name, but
different parameter list and different definitions. This is called method
overloading.
Method overloading is used when objects are required to perform similar
tasks but using different input parameters. When we call a method in an object,
java matches up the method name first and then number and type of parameters
to decide which one of the definitions to execute. The methods return type does
not play any role in this.

21
OOP using JAVA

The following program illustrates the concept of method overloading in


java.
Aim: To find the sum of two integers, two float values, two double values and
two characters
Program
//MethodOverload.java
class MethodOverload
{
int sum(int x,int y)
{
int z;
z=x+y;
return z;
}
double sum(double x, double y)
{
double z;
z=x+y;
return z;
}
int sum(char x, char y)
{
int z;
z=x+y;
return z;
}
public static void main(String[] args)
{
MethodOverload o1=new MethodOverload();
System.out.println("The integer sum is:" + o1.sum(10,20));
System.out.println("The double sum is:" + o1.sum(10.5,12.5));
System.out.println("The character sum is:" +o1.sum('a','b'));
}
}
Output:

22
OOP using JAVA

Constructor Overloading
Like methods, constructors can also be overloaded. Appropriate
constructor is called as per the parameters we pass at the time of object creation.
In the following program, the constructor Demo() is overloaded 3 times.
Aim: To illustrate the concept of constructor overloading.
Program
//Demo.java
class Demo
{
int x,y;
Demo() // Default constructor
{
x=10;
y=20;
System.out.println("From default constructor");
}
Demo(int a) //Single parameterized constructor
{
x=a;
y=a;
System.out.println("From Single parameterized constructor");
}
Demo(int a, int b) //Double parameterized constructor
{
x=a;
y=b;
System.out.println("From double parameterized constructor");
}
void display()
{
System.out.println("The values are, x= " + x + " and y=" + y);
}
public static void main(String[] args)
{
Demo d1=new Demo(); //calling default constructor
d1.display();
Demo d2=new Demo(30); // calling Single parameterized
constructor
d2.display();

23
OOP using JAVA

Demo d3=new Demo(40,50); //calling double parameterized


constructor
d3.display();
}
}
Output:

****************************************************************
‘this’ keyword
In Java, this is a reference variable that refers to the current object.
Generally we write instance variables, constructors and methods in a class. All
these members are referenced by ‘this’. When an object is created to a class, a
default reference is also created internally to the object, as shown in fig.

Usage of Java this keyword


1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
Program:
class Sample
{
int x; //instance variable
Sample() //default constructor
{
24
OOP using JAVA

this(55); //call present class para constructor and send value


this.access(); //call present class method
}
Sample(int x) //parameterized constructor
{
this.x=x; //refer present class instance variable
}
void access()
{
System.out.println("x="+x);
}
}
class ThisDemo
{
public static void main(String args[])
{
Sample s=new Sample();
}
}

Output:

****************************************************************
Inheritance
Definition:
The process of obtaining the data members and member functions from
one class to another class is known as Inheritance.
The class which is giving data members and member functions to some
other class is known as base/ super / parent class.
The class which is retrieving or obtaining the data members and member
functions is known as derived/sub/child class.
A Derived class contains some of features of its own plus some of
the data members from base class.

25
OOP using JAVA

Advantages of Inheritance
 Application development time is less.
 Application amount of memory space is less.
 Redundancy (Repetition) of the code is reduced.
Syntax for INHERITING the features from base class to derived class:
class <clsname-2> extends <clsname-1>
{
Variable declaration;
Method definition;
}
Extends is a keyword which is used for inheriting the data members and
methods from base class to the derived class and it also improves functionality of
derived class.
Types of Inheritances (Reusable Techniques)
Based on getting the features from one class to some other class, in java
we have the following types of reusable techniques.
 Single Inheritance (only one super class)
 Multilevel Inheritance ( several super classes)
 Multiple Inheritance (several super class, many sub classes)
 Hierarchical Inheritance (one super class, many sub classes)
Single Inheritance
It is one it contains a single base class and a single derived class. It is shown
in below.

The following program illustrates the concept of Simple Inheritance


Aim: Program to find the area of the room and the volume of a bed room.
Program
//InheritTest.java

26
OOP using JAVA

class Room
{
float len, bre;
Room(float x, float y)
{
len=x;
bre=y;
}
float roomArea()
{
return (len*bre);
}
}
class BedRoom extends Room
{
float hei;
BedRoom(float x, float y, float z)
{
super(x,y);
hei=z;
}
float volume()
{
return (len*bre*hei);
}
}
class InheritTest
{
public static void main(String args[])
{
BedRoom r1=new BedRoom(12.2f,15.2f,10.3f);
float area=r1.roomArea();
float vol=r1.volume();

System.out.println("The area of the room is: " + area);


System.out.println("The volume of the bed room is: " + vol);
}
}

27
OOP using JAVA

Output:

Multilevel Inheritance
It is one in which it contains one base class and one derived class and
multiple intermediate base classes.( An intermediate base class is one, in one
context it acts as a derived class, in another context the same class acts as a base
class). It is shown in below.

Multiple Inheritance
It is one in which it contains multiple base classes and a s ingle derived
class. It is shown in below.

28
OOP using JAVA

The concept of multiple inheritance is not supported in java directly but it


can be supported through the concept of interfaces.
Hierarchical Inheritance
It is one in which there exists a single base class and multiple derived
classes. It is shown in below.

****************************************************************
Super keyword in Java.
Subclass Constructor (‘super’ keyword):
A Subclass constructor is used to construct the instance variables of both
the subclass and the super class. The subclass constructor uses the keyword super
to invoke the constructor method of the super class. The super keyword is used
subject to the following conditions.
 super may only be used within a subclass constructor method.
 The call to super class constructor must appear as the first statement within
the subclass constructor.
 The parameters in the super call must match the order and type of the
instance variables declared in the super class.

Final Classes and Methods


Final variables and methods:
All methods and variables can be overridden by default in subclasses. If
we wish to prevent the subclasses from overriding the members of the super class,
we can declare them as final using the keyword final as a modifier. For example
final int size=100;
final void showStatus()
{
----------
----------

29
OOP using JAVA

}
Making a method as final ensures that the functionality in this method will
never be altered in any way. Similarly, the value of a final variable can never be
changed.
Final class:
If we don`t want to give features of base class to derived class then the
definition of the base class must be made as final.
Syntax: final class <clsname>
{
----------
}
Once the class is final, it never participates in inheritance process. In other
words final classes cannot be extended or inheritable.
Program:
final class Base
{
final void display()
{
System.out.println("This is a final method.");
}
}
class Derived extends Base
{
void display()
{
System.out.println("The final method is overridden.");
}
}
class Finaldemo
{
public static void main(String[] args)
{
Derived d = new Derived();
d.display();
final int x=10;
x=20;
}
}

30
OOP using JAVA

Output:

Note:
 Final variable values cannot be modified.
 Final methods cannot be overridden.
 Final classes cannot be inheritable.
****************************************************************

Dynamic binding

Dynamic binding in Java refers to the process of determining the specific


implementation of a method at runtime, based on the actual type of the object
being referred to, rather than the declared type of the reference variable. It is also
known as late binding or runtime polymorphism.

In Java, dynamic binding is primarily associated with method overriding,


where a subclass provides its own implementation of a method that is already
defined in its superclass. The specific method implementation to be executed is
determined dynamically based on the actual type of the object at runtime.

Example :

class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {

31
OOP using JAVA

public void draw() {


System.out.println("Drawing a rectangle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Rectangle();

shape1.draw(); // Output: Drawing a circle


shape2.draw(); // Output: Drawing a rectangle
}
}

In the above example, we have a Shape class and two subclasses: Circle
and Rectangle. Each subclass overrides the draw() method inherited from the
Shape class.In the main method, we created two shape objects: shape1 of type
Circle and shape2 of type Rectangle. Although the reference type is Shape, the
actual objects being referred to are Circle and Rectangle.

When we call the draw() method on shape1 and shape2, the JVM
dynamically binds the appropriate version of the draw() method at runtime based
on the actual type of the object.

Since shape1 refers to a Circle object, the draw() method in the Circle class
is invoked, and the output is "Drawing a circle". Similarly, since shape2 refers to
a Rectangle object, the draw() method in the Rectangle class is invoked, and the
output is "Drawing a rectangle".

This dynamic binding allows us to write code that works with a generic
reference type (Shape), but at runtime, the correct method implementation is
determined based on the actual object type being referred to. This flexibility and
polymorphic behaviour is one of the key advantages of dynamic binding in Java.

********************************************************
Method Overriding
The process of redefining the same method for many number of
implementations is called as method overriding.

32
OOP using JAVA

The method overriding is possible by defining a method in the sub class


that has the same name, same arguments and same return type as a method in the
super class.
Method Overriding = Method Heading is same + Method body is different.
The following program illustrates the concept of method overriding
Aim: To illustrate the concept of method overriding in java.
Program:
//OverrideTest.java
class Super
{
int x;
Super(int x)
{
this.x=x;
}
void display() // method defined
{
System.out.println("The value of x at super is: " + x);
}
}
class Sub extends Super
{
int y;
Sub(int x, int y)
{
super(x);
this.y=y;
}
void display() //method defined again
{
System.out.println("The value of x at sub class is: " + x);
System.out.println("The value of y at sub class is: " + y);
}
}
class OverrideTest
{
public static void main(String args[])
{
Sub s1=new Sub(100,200);
s1.display();

33
OOP using JAVA

}
}
Output:

****************************************************************
Abstract Methods and Classes
Abstract Method or Undefined method:
An abstract method is one which does not contain any definition/body but
it contains only prototype/declaration.
In order to make undefined methods as abstract methods, we need to write
abstract keyword before the method prototype.
Syntax for abstract method:
abstract return_type method_name ( list_args);
When we are declaring a method as an abstract method, that means, we can
indicate that a method must always be redefined in a subclass, thus making
overriding compulsory.
Example:
abstract void sum();
abstract void sum(int x, int y);
abstract class
If a class is containing one or more abstract methods then that class should
also be declared as an abstract class.
Syntax for abstract class
abstract class <clsname>
{
----------
abstract return_type method_name ( list_args);
---------
}

34
OOP using JAVA

Example
abstract class Base
{
abstract void calculate(int x);
}
class Derived1 extends Base
{
void calculate(int x)
{
System.out.println("Square="+(x*x));
}
}
class Derived2 extends Base
{
void calculate(int x)
{
System.out.println("Square root="+Math.sqrt(x));
}
}

class Derived3 extends Base


{
void calculate(int x)
{
System.out.println("Cube="+(x*x*x));
}
}
class Abstractdemo
{
public static void main(String args[])
{
Derived1 d1=new Derived1();
Derived2 d2=new Derived2();
Derived3 d3=new Derived3();
d1.calculate(8);
d2.calculate(9);
d3.calculate(10);
}
}

Output:

35

You might also like