Objects
and Classes in Java
Classes
We have already seen,
all code we write in java is inside a class. Standard java library provides
thousands of predefined java classes for different purposes such as for string
handling (String and StringBuffer), mathematical
functions (Math), UI design, date,
calendars, network programming etc. We can create our own class as per
requirement to design our application. Classes provide method of packing
logically related data and methods to work on that data. In java, data items
are called fields and functions are
called method. A class is
description of making of object that contains fields and methods.
Defining
a Class
Class is a user defined
data type. Once it is defined we can create variables of that type using
declaration similar to the basic data type (int, Boolean, double, String etc)
variable declaration. These variables of the classes are called instances of classes and they are actual
objects.
Syntax:
class ClassName{
Field declaration
(Variable declaration)
Method Declaration
(Function Declaration)
}
Field
Declaration: Data fields (variables) are
encapsulated inside the body of the class definition. These variables are
called instance variables because they are created when instance of the class
is created. Instance variables are created just like local variables. Example:
class MyRectangle{
int rectangleLength;
int rectangleWidth;
}
As shown in above
example class MyRectangle contains two integer type instance variables rectangleLength and rectangleWidth. Same type of
variables can be declared in same line also like:
class MyRectangle{
int rectangleLength, rectangleWidth;
}
Methods
Declaration: Methods are the very important part of
the class. A class with fields and without methods is useless because data of
this class cannot be accesses. Methods of a class are declared just after the
instance variables inside the class such as:
type methodName (Parameters)
{
Statements // Body of method
}
Type is return type of the method and parameters
are the list of arguments or parameters passed in the method.
Example:
class MyRectangle
{
int rectangleLength, rectangleWidth; //Instance Variables(Fields)
void setData(int x, int y) // Method setData
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle() // Method areaofRectangle
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
The method setData is
of void type because it doesn’t return any value. This method has two
parameters x and y. This method assigns values to instance variables of the
myRectangle class.
The method
areaofRectangle is integer type method. It computes the area of rectangle and
returns an integer value which is area of rectangle.
At present MyRectangle
class has two instance variables and two methods. We can add more instance
variables and methods to the class if required. Instance variable in a class
are accessible by all methods of that class. As in above example rectangleLength
and rectangleWidth
are instance variables and used in both the functions. The variable of a method
cannot be accessed by other methods because they are local to that method. In
above example area is
a local variable of method areaofRectangle
and cannot be accessed by outside of this method means this variable cannot be
used in method setData.
Objects
Object is a block of
memory that contains space to store all instance variables. Objects in java are
created using new operator which creates
an object of the given class. The new operator returns a handle which is a reference
to the object. Example
MyRectangle rectangleObj;
// Declaring Object
rectangleObj = new
MyRectangle(); // Creating/
instantiating object
OR
MyRectangle rectangleObj = new MyRectangle();
First statement declares
an object to hold reference of the object. Second line creates an object and
assigns reference of object to the variable. rectangleObj is an object of class MyRectangle.
Accessing
Class Members: We have created variables and now we can
assign values to these variables. There are two methods to access instance
variables. We cannot access instance variables directly, to access instance
variables we can use object of the class. Example First method:
rectangleObj.rectangleLength = 45;
rectangleObj.rectangleWidth
= 35;
We have already created
an object rectangleObj of class MyRectangle Now we have assigned values to instance variables of class MyRectangle using object rectangleObj.
Now the
object rectangleObj contains values for its instance variables, we can calculate area
of rectangle using dot (.) operator to access variables. Example:
int area = rectangleObj.rectangleLength * rectangleObj.rectangleWidth;
Another way
to assigning values to instance variable is using method setData() of MyRectangle Class.
Example Second Method:
MyRectangle newObj = new MyRectangle();
newObj.setData(34, 30);
First line creates new
object newObj of class MyRectangle In second line newObj is used to call function setData()
and pass values 34 and 30 for x and y parameters to the function setData() These
values are then assigned to instance variables rectangleLength and rectangleWidth .
Now object newObj contains the values for instance variables
we can call method areaofRectangle
to get area of rectangle.
int rectArea =
newObj.areaofRectangle();
Example:
class MyRectangle
{
int rectangleLength, rectangleWidth;
void setData(int x, int y)
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
public class RectProgram
{
public static void main(String[] args)
{
int rectArea, rectArea2;
//
Assigning value to instance variables directly
MyRectangle rectangleObj = new MyRectangle();
rectangleObj.rectangleLength = 30;
rectangleObj.rectangleWidth = 20;
rectArea = rectangleObj.rectangleLength * rectangleObj.rectangleWidth;
//
Assigning values to instance variable using method setData
MyRectangle newObj = new MyRectangle();
newObj.setData(50, 40);
rectArea2 =
newObj.areaofRectangle();
System.out.println("Area using first method: rectArea: " + rectArea);
System.out.println("Area using Second method: rectArea2: " + rectArea2);
}
}
The output
of this program is:
Area
using first method: rectArea: 600
Area
using Second method: rectArea2: 2000
Constructors
All objects
should assign initial values to instance variables of the class as we have seen
in above examples. We have discussed two ways of assigning values to instance
variable, one is using dot operator and assign value directly to the variables,
another way is by using a function setData.
But is will be easy and simple to assign values to the variable when an object
is created. Java provides a special kind of method called constructor to initialize objects when they are created. The name
of the constructor and class is same. Constructor
doesn’t have return type not even void because they return instance of class
itself. In previous example we use a method setData to initialize variables, Instead of that method we can use
constructor.
Example:
class MyRectangle // Class defination
{
int rectangleLength, rectangleWidth;
MyRectangle(int x, int y) // Constructor Defination
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
The name of
the class is MyRectangle and name of
a method is also MyRectangle which is
actually constructor the class. The constructor uses two parameters and not
returning any value MyRectangle(int x, int y).
Constructor
is called with parameters when we want to create an object or instance of the
class. The constructor method returns instance of the class.
Example:
class MyRectangle // Class definition
{
int rectangleLength, rectangleWidth;
MyRectangle(int x, int y) // Constructor Definition
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
public class RectangleProgram
{
public static void main(String[] args)
{
int rectArea;
//
Calling Constructor
MyRectangle rectangleObj = new MyRectangle(20,10);
rectArea =
rectangleObj.areaofRectangle();
System.out.println("Area of rectangle:
" + rectArea);
}
}
The output
of this program is: Area of
rectangle: 200
The
statement MyRectangle rectangleObj = new MyRectangle(20,10); calls constructor and returns instance of class.
Method Overloading
In Java we
can create more than one method with the same name but different parameters,
return types and definitions. This is called method overloading. When we call one of these methods, java decides
which method to call on the basis of number and type of parameters. This
process is called polymorphism. The
parameter list of each method should be unique (different) in method
overloading. Methods return type doesn’t play any role in method overloading
only number and type of parameter should be different.
Example:
class MyRectangle // Class definition
{
int rectangleLength, rectangleWidth;
MyRectangle(int x, int y) // Constructor 1
{
rectangleLength = x;
rectangleWidth = y;
}
MyRectangle(int x) // Constructor 2
{
rectangleLength = rectangleWidth = x;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
public class RectangleProgram
{
public static void main(String[] args)
{
int rectArea, rectArea2;
//
Calling Constructor 1
MyRectangle rectangleObj = new MyRectangle(20,10);
rectArea =
rectangleObj.areaofRectangle();
System.out.println("Area using Constructor 1:
" + rectArea);
//
Calling Constructor 2
MyRectangle rectangleObj2 = new MyRectangle(20);
rectArea2 = rectangleObj2.areaofRectangle();
System.out.println("Area using Constructor 2:
" + rectArea2);
}
}
The output
of this program is:
Area
using Constructor 1: 200
Area
using Constructor 2: 400
In this
example we have created two constructor methods with same name as of class MyRectangle.
First method has two integer type parameters MyRectangle(int x, int y) and second method has only one integer type parameter MyRectangle(int x). When call these methods
with parameters java will decide which method has been called on the basis of
parameters. When we called method MyRectangle rectangleObj = new MyRectangle(20,10); java
created an object rectangleObj and calculated areofRectangle = 200. And when we
called second method MyRectangle rectangleObj2 = new MyRectangle(20); Java
created an object rectangleObj2 and
calculated areofRectangle = 400. Means
it has created two separate instances of both the objects in the memory.
We will see
one more example of method overloading with different type of parameters to a
method. In this example methods are not constructors.
Example:
class AddTowValues // Class
definition
{
int addition(int x, int y) // Constructor 1
{
int z = x + y;
return z;
}
String addition(String first, String
second)
{
String temp = first + second;
return temp;
}
}
public class MethodOverload
{
public static void main(String[] args)
{
int tempResult;
String tempStrResult;
AddTowValues t = new AddTowValues();
tempResult = t.addition(20, 30);
System.out.println("Addition of two integers:
" + tempResult);
tempStrResult = t.addition("Method ", "Overloading");
System.out.println("Addition of two integers:
" + tempStrResult);
}
}
The output
of this program is:
Addition
of two integers: 50
Addition
of two integers: Method Overloading
We have
created a class named AddTowValues which has two methods
with same name first is: int addition(int x, int y) which has two integer type parameters. This method adds the value
of both the parameters and returns sum of these values. The second method is: String
addition(String first, String second) which has
string type parameters. This method concatenates both the parameter strings and
returns concatenated string.
To call
these methods first we will need to create instance of the class AddTowValues t = new AddTowValues(). Here t is instance of the class.
Then we call function using dot operator tempResult
= t.addition(20, 30). We have called this method
by supplying integer type parameter which returns integer type value. Similarly
we called same function using string parameters tempStrResult = t.addition("Method
", "Overloading"). This method returns string
type value.
Static Members
We have seen that basically
class has two sections variables and methods. These variables are called instance variables and methods called instance methods
because
they are limited to the instance of the class. Each time when instance of a
class is created these variables and methods are created for that instance they
are not accessible outside of that instance. These variables are accessible by
using objects and dot operator as we have seen in previous examples.
We can also define a
member (method or variable) that is common to all objects of same class and can
be accessed without using a particular object. Means that member belongs to the
class as a whole not only to object of that class. Such members (Variable or
Method) can be defined as follows:
static int totalNuber;
static int biggerNumber(int x, int y);
These members are
called static members. As these
variables and methods are associated with class not with individual object, these
static variables are called class
variables and static methods are called class methods. They are different from instance variables and
instance methods. We use static variables when we want to use a variable common
to all instances of a class. Java creates only one copy of static variable and
that can be used even without creating instance of the class. Static methods
can also be called directly without creating objects.
Example:
class AddSubtract
{
static int addition(int x, int y)
{
int z = x + y;
return z;
}
static int subtraction(int x, int y)
{
int z = x - y;
return z;
}
}
public class StaticMembers
{
public static void main(String[] args)
{
int result1 = AddSubtract.addition(5, 6);
int result2 = AddSubtract.subtraction(result1, 4);
System.out.println("Result2: " + result2);
}
}
The output of the
program is: Result2: 7
As shown in above example static methods are
called directly using classes without creating any object of the class. int result1 =
AddSubtract.addition(5, 6). Static
methods can only call other static methods and can access only static data.
Inheritance
Java support
reusability, we can create a class and reuse it instead of creating same class
again. This can be done by creating a new class and using the properties of old
class in new class. This process of deriving a new class from old class is
called inheritance. The old class is
called base class or super class and the new class which inherits properties (variables
and methods) of base class is called sub
class, derived class or child class.
There are various types
of inheritance:
Single inheritance: one
super class and one sub class.
Multiple inheritances: several
super classes and one sub class. (Java doesn’t support it).
Hierarchical
inheritance: one super class and several sub classes.
Multilevel inheritance:
derived from a derived class (Super class -> sub class -> sub class).
Example:
class Room
{
int roolLength;
int roomWidth;
Room(int x, int y)
{
roolLength = x;
roomWidth = y;
}
int area()
{
return (roolLength * roomWidth);
}
}
class BedRoom extends Room
{
int roomHeight;
BedRoom(int x, int y, int z)
{
super (x,y);
roomHeight = z;
}
int volume()
{
return (roolLength * roomWidth * roomHeight);
}
}
public class InstanceProgram
{
public static void main(String[] args)
{
BedRoom myRoom = new BedRoom(10,15,9);
int roomVolume = myRoom.volume();
int roomArea = myRoom.area();
System.out.println("Volume of the room is:
" + roomVolume);
System.out.println("Area of the room is:
" + roomArea);
}
}
The output
of this program is:
Volume
of the room is: 1350
Area
of the room is: 150
Room is super class. roolLength and roomWidth are variables of this class, method Room(int x, int y) is constructor method of Room class and int area() is method of this class which calculates area of room and returns
integer value (area of room).
BedRoom is
subclass of Room class. To subclass of a class we use “extends”. The statement class BedRoom extends Room,
creates a class BedRoom which inherits the properties of Room class. BedRoom
class has a variable roomHeight but
it can also use the variables of super class Room. BedRoom class has a
constructor method BedRoom(int x, int y, int z). When instance of
class BedRoom is created then this
method initializes variables of both the super class (Room) and sub class (BedRoom).
Constructor has directly initialized the variable of BedRoom class by statement
roomHeight = z but
to initialize variables of super class (Room) it has called method super (x,y). The method
super calls the constructor of super
class (Room) and the constructor of super class then initializes variables of super class (roolLength and roomWidth). This way
variables of both the classes are initialized, class Room can access only its
own variables (roolLength and roomWidth)
but calss BedRoom can access variables and mthods of both the classes.
The statement BedRoom myRoom = new BedRoom(10,15,9) calls constructor and creates an object myRoom of subclass BedRoom which calls class Room by using method super.
Overriding
Methods
We have seen in
previous topic that a method defined in super class can be inherited in sub
class. We created an object of subclass to access the method of super class,
without redefining this method in subclass. But in some situations we want same
method to behave differently means this method has different definition and
produce different result. In this situation we have two methods one in super
class and another one is in sub class, with same name, same parameters with
same data types and same return type. This process of having same method in
both super class and sub class is called overriding methods. When we call this
type of method then method defined in subclass will be called.
Example:
class SuperClass
{
int x;
SuperClass(int x)
{
this.x = x;
}
void outPut()
{
System.out.println("Out Put from SuperClass: x = " + x);
}
}
class SubClass extends SuperClass
{
int y;
SubClass(int x, int y)
{
super(x);
this.y = y;
}
void outPut()
{
System.out.println("Out Put from SubClass: y =
" + y);
}
}
public class FirstJavaProgram
{
public static void main(String[] args)
{
SubClass myClass = new SubClass(10,15);
myClass.outPut();
}
}
The output of the
program is: Out Put from SubClass: y =
15
We have created a super
class with name SuperClass. Ther is a statement this.x = x; in this statement name of instance variable (x) is same as the
name of parameter passed to constructor SuperClass(int x); in this condition when name of two variables is same we
use this with the instance variable (Variable defined outside of the
method). Here this.x is
instance variable x. Means when we have same name of local variable (or
parameter) of a method as the name of instance variable then we have to use this keyword then dot operator and name
of the variable such as (this.variable). SuperClass contains a method void
outPut() which prints the value of x on the screen
We have also created
sub class with name SubClass which also contains a method void
outPut(),
means the method void outPut() is present in both the classes
subclass and superClass. To execute this function we created an object myClass of subclass. Then we called method
myClass.outPut(); which displays the method of subClass.
Final
Variables, Methods and Classes
Sub classes can
override all methods and variables of a super class, in some situations we
don’t want that. To protect methods and variables from overridden we use a key
word fine at the time of declaration of the class.
Example:
final int MAX = 100; //Declaration
of final variable
final void uotPut() // Final function declaration
When we
declare a variable or method with keyword final in super class, we cannot
declare a variable and method with same name in sub class. This type of
variables is called final variables
and methods are called final methods.
Similarly
if we don’t want to allow creating a sub class of a class then we declare that
class final keyword.
Example:
final class Room {...} // Final class
We cannot create sub
class of this Room class. This type of classes is called final class.
Abstract Methods and Classes
We have
seen in previous example that using final
keyword we ensure that method is not redefined in the subclass. Java also
provides a facility by using that we can do just opposite of that, we can
ensure that method is redefined in the subclass, thus making overriding
compulsory. This can be done by using a keyword abstract.
Example:
abstract class SuperClass
{ ...................
abstract void uotPut();
.............
}
We cannot
create object of abstract class directly, to access an abstract class we will
need to create a sub class of an abstracted class, then we will create an
object of sub class and access abstracted class using this object. The abstract
methods of abstract class must be defined in subclass. Constructor of the class
and static methods of a class cannot be declared as abstract methods.
Visibility Control
As we have seen in
previous examples that a sub class can inherits variables and methods of a
super class using keyword extends. In some situations we may need to restrict
access to certain variables and methods from outside the class. We can do this
by applying visibility modifiers to
instance variables and methods. Visibility modifiers are also known as access modifiers. In java there are
three visibility modifiers: Public, Private and Protected.
Public Access: The variables and methods
are visible to entire class in which they are declared. We can make them
visible in other classes outside of the class using keyword public.
Example:
public int value;
public void addition() {...}
To make fields (variables
and methods)
visible everywhere we declare them public.
They are accessible in all packages.
Friendly
Access: When
no modifier is specified for the variables and methods they are considered as
friendly accessible. Friendly accessibObjects
and Classes in Java
Classes
We have already seen,
all code we write in java is inside a class. Standard java library provides
thousands of predefined java classes for different purposes such as for string
handling (String and StringBuffer), mathematical
functions (Math), UI design, date,
calendars, network programming etc. We can create our own class as per
requirement to design our application. Classes provide method of packing
logically related data and methods to work on that data. In java, data items
are called fields and functions are
called method. A class is
description of making of object that contains fields and methods.
Defining
a Class
Class is a user defined
data type. Once it is defined we can create variables of that type using
declaration similar to the basic data type (int, Boolean, double, String etc)
variable declaration. These variables of the classes are called instances of classes and they are actual
objects.
Syntax:
class ClassName{
Field declaration
(Variable declaration)
Method Declaration
(Function Declaration)
}
Field
Declaration: Data fields (variables) are
encapsulated inside the body of the class definition. These variables are
called instance variables because they are created when instance of the class
is created. Instance variables are created just like local variables. Example:
class MyRectangle{
int rectangleLength;
int rectangleWidth;
}
As shown in above
example class MyRectangle contains two integer type instance variables rectangleLength and rectangleWidth. Same type of
variables can be declared in same line also like:
class MyRectangle{
int rectangleLength, rectangleWidth;
}
Methods
Declaration: Methods are the very important part of
the class. A class with fields and without methods is useless because data of
this class cannot be accesses. Methods of a class are declared just after the
instance variables inside the class such as:
type methodName (Parameters)
{
Statements // Body of method
}
Type is return type of the method and parameters
are the list of arguments or parameters passed in the method.
Example:
class MyRectangle
{
int rectangleLength, rectangleWidth; //Instance Variables(Fields)
void setData(int x, int y) // Method setData
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle() // Method areaofRectangle
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
The method setData is
of void type because it doesn’t return any value. This method has two
parameters x and y. This method assigns values to instance variables of the
myRectangle class.
The method
areaofRectangle is integer type method. It computes the area of rectangle and
returns an integer value which is area of rectangle.
At present MyRectangle
class has two instance variables and two methods. We can add more instance
variables and methods to the class if required. Instance variable in a class
are accessible by all methods of that class. As in above example rectangleLength
and rectangleWidth
are instance variables and used in both the functions. The variable of a method
cannot be accessed by other methods because they are local to that method. In
above example area is
a local variable of method areaofRectangle
and cannot be accessed by outside of this method means this variable cannot be
used in method setData.
Objects
Object is a block of
memory that contains space to store all instance variables. Objects in java are
created using new operator which creates
an object of the given class. The new operator returns a handle which is a reference
to the object. Example
MyRectangle rectangleObj;
// Declaring Object
rectangleObj = new
MyRectangle(); // Creating/
instantiating object
OR
MyRectangle rectangleObj = new MyRectangle();
First statement declares
an object to hold reference of the object. Second line creates an object and
assigns reference of object to the variable. rectangleObj is an object of class MyRectangle.
Accessing
Class Members: We have created variables and now we can
assign values to these variables. There are two methods to access instance
variables. We cannot access instance variables directly, to access instance
variables we can use object of the class. Example First method:
rectangleObj.rectangleLength = 45;
rectangleObj.rectangleWidth
= 35;
We have already created
an object rectangleObj of class MyRectangle Now we have assigned values to instance variables of class MyRectangle using object rectangleObj.
Now the
object rectangleObj contains values for its instance variables, we can calculate area
of rectangle using dot (.) operator to access variables. Example:
int area = rectangleObj.rectangleLength * rectangleObj.rectangleWidth;
Another way
to assigning values to instance variable is using method setData() of MyRectangle Class.
Example Second Method:
MyRectangle newObj = new MyRectangle();
newObj.setData(34, 30);
First line creates new
object newObj of class MyRectangle In second line newObj is used to call function setData()
and pass values 34 and 30 for x and y parameters to the function setData() These
values are then assigned to instance variables rectangleLength and rectangleWidth .
Now object newObj contains the values for instance variables
we can call method areaofRectangle
to get area of rectangle.
int rectArea =
newObj.areaofRectangle();
Example:
class MyRectangle
{
int rectangleLength, rectangleWidth;
void setData(int x, int y)
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
public class RectProgram
{
public static void main(String[] args)
{
int rectArea, rectArea2;
//
Assigning value to instance variables directly
MyRectangle rectangleObj = new MyRectangle();
rectangleObj.rectangleLength = 30;
rectangleObj.rectangleWidth = 20;
rectArea = rectangleObj.rectangleLength * rectangleObj.rectangleWidth;
//
Assigning values to instance variable using method setData
MyRectangle newObj = new MyRectangle();
newObj.setData(50, 40);
rectArea2 =
newObj.areaofRectangle();
System.out.println("Area using first method: rectArea: " + rectArea);
System.out.println("Area using Second method: rectArea2: " + rectArea2);
}
}
The output
of this program is:
Area
using first method: rectArea: 600
Area
using Second method: rectArea2: 2000
Constructors
All objects
should assign initial values to instance variables of the class as we have seen
in above examples. We have discussed two ways of assigning values to instance
variable, one is using dot operator and assign value directly to the variables,
another way is by using a function setData.
But is will be easy and simple to assign values to the variable when an object
is created. Java provides a special kind of method called constructor to initialize objects when they are created. The name
of the constructor and class is same. Constructor
doesn’t have return type not even void because they return instance of class
itself. In previous example we use a method setData to initialize variables, Instead of that method we can use
constructor.
Example:
class MyRectangle // Class defination
{
int rectangleLength, rectangleWidth;
MyRectangle(int x, int y) // Constructor Defination
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
The name of
the class is MyRectangle and name of
a method is also MyRectangle which is
actually constructor the class. The constructor uses two parameters and not
returning any value MyRectangle(int x, int y).
Constructor
is called with parameters when we want to create an object or instance of the
class. The constructor method returns instance of the class.
Example:
class MyRectangle // Class definition
{
int rectangleLength, rectangleWidth;
MyRectangle(int x, int y) // Constructor Definition
{
rectangleLength = x;
rectangleWidth = y;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
public class RectangleProgram
{
public static void main(String[] args)
{
int rectArea;
//
Calling Constructor
MyRectangle rectangleObj = new MyRectangle(20,10);
rectArea =
rectangleObj.areaofRectangle();
System.out.println("Area of rectangle:
" + rectArea);
}
}
The output
of this program is: Area of
rectangle: 200
The
statement MyRectangle rectangleObj = new MyRectangle(20,10); calls constructor and returns instance of class.
Method Overloading
In Java we
can create more than one method with the same name but different parameters,
return types and definitions. This is called method overloading. When we call one of these methods, java decides
which method to call on the basis of number and type of parameters. This
process is called polymorphism. The
parameter list of each method should be unique (different) in method
overloading. Methods return type doesn’t play any role in method overloading
only number and type of parameter should be different.
Example:
class MyRectangle // Class definition
{
int rectangleLength, rectangleWidth;
MyRectangle(int x, int y) // Constructor 1
{
rectangleLength = x;
rectangleWidth = y;
}
MyRectangle(int x) // Constructor 2
{
rectangleLength = rectangleWidth = x;
}
int areaofRectangle()
{
int area = rectangleLength * rectangleWidth;
return(area);
}
}
public class RectangleProgram
{
public static void main(String[] args)
{
int rectArea, rectArea2;
//
Calling Constructor 1
MyRectangle rectangleObj = new MyRectangle(20,10);
rectArea =
rectangleObj.areaofRectangle();
System.out.println("Area using Constructor 1:
" + rectArea);
//
Calling Constructor 2
MyRectangle rectangleObj2 = new MyRectangle(20);
rectArea2 = rectangleObj2.areaofRectangle();
System.out.println("Area using Constructor 2:
" + rectArea2);
}
}
The output
of this program is:
Area
using Constructor 1: 200
Area
using Constructor 2: 400
In this
example we have created two constructor methods with same name as of class MyRectangle.
First method has two integer type parameters MyRectangle(int x, int y) and second method has only one integer type parameter MyRectangle(int x). When call these methods
with parameters java will decide which method has been called on the basis of
parameters. When we called method MyRectangle rectangleObj = new MyRectangle(20,10); java
created an object rectangleObj and calculated areofRectangle = 200. And when we
called second method MyRectangle rectangleObj2 = new MyRectangle(20); Java
created an object rectangleObj2 and
calculated areofRectangle = 400. Means
it has created two separate instances of both the objects in the memory.
We will see
one more example of method overloading with different type of parameters to a
method. In this example methods are not constructors.
Example:
class AddTowValues // Class
definition
{
int addition(int x, int y) // Constructor 1
{
int z = x + y;
return z;
}
String addition(String first, String
second)
{
String temp = first + second;
return temp;
}
}
public class MethodOverload
{
public static void main(String[] args)
{
int tempResult;
String tempStrResult;
AddTowValues t = new AddTowValues();
tempResult = t.addition(20, 30);
System.out.println("Addition of two integers:
" + tempResult);
tempStrResult = t.addition("Method ", "Overloading");
System.out.println("Addition of two integers:
" + tempStrResult);
}
}
The output
of this program is:
Addition
of two integers: 50
Addition
of two integers: Method Overloading
We have
created a class named AddTowValues which has two methods
with same name first is: int addition(int x, int y) which has two integer type parameters. This method adds the value
of both the parameters and returns sum of these values. The second method is: String
addition(String first, String second) which has
string type parameters. This method concatenates both the parameter strings and
returns concatenated string.
To call
these methods first we will need to create instance of the class AddTowValues t = new AddTowValues(). Here t is instance of the class.
Then we call function using dot operator tempResult
= t.addition(20, 30). We have called this method
by supplying integer type parameter which returns integer type value. Similarly
we called same function using string parameters tempStrResult = t.addition("Method
", "Overloading"). This method returns string
type value.
Static Members
We have seen that basically
class has two sections variables and methods. These variables are called instance variables and methods called instance methods
because
they are limited to the instance of the class. Each time when instance of a
class is created these variables and methods are created for that instance they
are not accessible outside of that instance. These variables are accessible by
using objects and dot operator as we have seen in previous examples.
We can also define a
member (method or variable) that is common to all objects of same class and can
be accessed without using a particular object. Means that member belongs to the
class as a whole not only to object of that class. Such members (Variable or
Method) can be defined as follows:
static int totalNuber;
static int biggerNumber(int x, int y);
These members are
called static members. As these
variables and methods are associated with class not with individual object, these
static variables are called class
variables and static methods are called class methods. They are different from instance variables and
instance methods. We use static variables when we want to use a variable common
to all instances of a class. Java creates only one copy of static variable and
that can be used even without creating instance of the class. Static methods
can also be called directly without creating objects.
Example:
class AddSubtract
{
static int addition(int x, int y)
{
int z = x + y;
return z;
}
static int subtraction(int x, int y)
{
int z = x - y;
return z;
}
}
public class StaticMembers
{
public static void main(String[] args)
{
int result1 = AddSubtract.addition(5, 6);
int result2 = AddSubtract.subtraction(result1, 4);
System.out.println("Result2: " + result2);
}
}
The output of the
program is: Result2: 7
As shown in above example static methods are
called directly using classes without creating any object of the class. int result1 =
AddSubtract.addition(5, 6). Static
methods can only call other static methods and can access only static data.
Inheritance
Java support
reusability, we can create a class and reuse it instead of creating same class
again. This can be done by creating a new class and using the properties of old
class in new class. This process of deriving a new class from old class is
called inheritance. The old class is
called base class or super class and the new class which inherits properties (variables
and methods) of base class is called sub
class, derived class or child class.
There are various types
of inheritance:
Single inheritance: one
super class and one sub class.
Multiple inheritances: several
super classes and one sub class. (Java doesn’t support it).
Hierarchical
inheritance: one super class and several sub classes.
Multilevel inheritance:
derived from a derived class (Super class -> sub class -> sub class).
Example:
class Room
{
int roolLength;
int roomWidth;
Room(int x, int y)
{
roolLength = x;
roomWidth = y;
}
int area()
{
return (roolLength * roomWidth);
}
}
class BedRoom extends Room
{
int roomHeight;
BedRoom(int x, int y, int z)
{
super (x,y);
roomHeight = z;
}
int volume()
{
return (roolLength * roomWidth * roomHeight);
}
}
public class InstanceProgram
{
public static void main(String[] args)
{
BedRoom myRoom = new BedRoom(10,15,9);
int roomVolume = myRoom.volume();
int roomArea = myRoom.area();
System.out.println("Volume of the room is:
" + roomVolume);
System.out.println("Area of the room is:
" + roomArea);
}
}
The output
of this program is:
Volume
of the room is: 1350
Area
of the room is: 150
Room is super class. roolLength and roomWidth are variables of this class, method Room(int x, int y) is constructor method of Room class and int area() is method of this class which calculates area of room and returns
integer value (area of room).
BedRoom is
subclass of Room class. To subclass of a class we use “extends”. The statement class BedRoom extends Room,
creates a class BedRoom which inherits the properties of Room class. BedRoom
class has a variable roomHeight but
it can also use the variables of super class Room. BedRoom class has a
constructor method BedRoom(int x, int y, int z). When instance of
class BedRoom is created then this
method initializes variables of both the super class (Room) and sub class (BedRoom).
Constructor has directly initialized the variable of BedRoom class by statement
roomHeight = z but
to initialize variables of super class (Room) it has called method super (x,y). The method
super calls the constructor of super
class (Room) and the constructor of super class then initializes variables of super class (roolLength and roomWidth). This way
variables of both the classes are initialized, class Room can access only its
own variables (roolLength and roomWidth)
but calss BedRoom can access variables and mthods of both the classes.
The statement BedRoom myRoom = new BedRoom(10,15,9) calls constructor and creates an object myRoom of subclass BedRoom which calls class Room by using method super.
Overriding
Methods
We have seen in
previous topic that a method defined in super class can be inherited in sub
class. We created an object of subclass to access the method of super class,
without redefining this method in subclass. But in some situations we want same
method to behave differently means this method has different definition and
produce different result. In this situation we have two methods one in super
class and another one is in sub class, with same name, same parameters with
same data types and same return type. This process of having same method in
both super class and sub class is called overriding methods. When we call this
type of method then method defined in subclass will be called.
Example:
class SuperClass
{
int x;
SuperClass(int x)
{
this.x = x;
}
void outPut()
{
System.out.println("Out Put from SuperClass: x = " + x);
}
}
class SubClass extends SuperClass
{
int y;
SubClass(int x, int y)
{
super(x);
this.y = y;
}
void outPut()
{
System.out.println("Out Put from SubClass: y =
" + y);
}
}
public class FirstJavaProgram
{
public static void main(String[] args)
{
SubClass myClass = new SubClass(10,15);
myClass.outPut();
}
}
The output of the
program is: Out Put from SubClass: y =
15
We have created a super
class with name SuperClass. Ther is a statement this.x = x; in this statement name of instance variable (x) is same as the
name of parameter passed to constructor SuperClass(int x); in this condition when name of two variables is same we
use this with the instance variable (Variable defined outside of the
method). Here this.x is
instance variable x. Means when we have same name of local variable (or
parameter) of a method as the name of instance variable then we have to use this keyword then dot operator and name
of the variable such as (this.variable). SuperClass contains a method void
outPut() which prints the value of x on the screen
We have also created
sub class with name SubClass which also contains a method void
outPut(),
means the method void outPut() is present in both the classes
subclass and superClass. To execute this function we created an object myClass of subclass. Then we called method
myClass.outPut(); which displays the method of subClass.
Final
Variables, Methods and Classes
Sub classes can
override all methods and variables of a super class, in some situations we
don’t want that. To protect methods and variables from overridden we use a key
word fine at the time of declaration of the class.
Example:
final int MAX = 100; //Declaration
of final variable
final void uotPut() // Final function declaration
When we
declare a variable or method with keyword final in super class, we cannot
declare a variable and method with same name in sub class. This type of
variables is called final variables
and methods are called final methods.
Similarly
if we don’t want to allow creating a sub class of a class then we declare that
class final keyword.
Example:
final class Room {...} // Final class
We cannot create sub
class of this Room class. This type of classes is called final class.
Abstract Methods and Classes
We have
seen in previous example that using final
keyword we ensure that method is not redefined in the subclass. Java also
provides a facility by using that we can do just opposite of that, we can
ensure that method is redefined in the subclass, thus making overriding
compulsory. This can be done by using a keyword abstract.
Example:
abstract class SuperClass
{ ...................
abstract void uotPut();
.............
}
We cannot
create object of abstract class directly, to access an abstract class we will
need to create a sub class of an abstracted class, then we will create an
object of sub class and access abstracted class using this object. The abstract
methods of abstract class must be defined in subclass. Constructor of the class
and static methods of a class cannot be declared as abstract methods.
Visibility Control
As we have seen in
previous examples that a sub class can inherits variables and methods of a
super class using keyword extends. In some situations we may need to restrict
access to certain variables and methods from outside the class. We can do this
by applying visibility modifiers to
instance variables and methods. Visibility modifiers are also known as access modifiers. In java there are
three visibility modifiers: Public, Private and Protected.
Public Access: The variables and methods
are visible to entire class in which they are declared. We can make them
visible in other classes outside of the class using keyword public.
Example:
public int value;
public void addition() {...}
To make fields (variables
and methods)
visible everywhere we declare them public.
They are accessible in all packages.
Friendly
Access: When
no modifier is specified for the variables and methods they are considered as
friendly accessible. Friendly accessible variables are available everywhere in
package, but not accessible outside of the package.
Protected
Access: Protected
access makes variables and method visible everywhere within a package and
subclasses in other packages.
Private
Access:
Private variables and functions are accessible within the class only. They
cannot be inherited in the subclasses so not visible in subclasses.
Private
protected Access:
It makes fields visible in all subclasses of different packages but not visible
to other classes in the same package.
le variables are available everywhere in
package, but not accessible outside of the package.
Protected
Access: Protected
access makes variables and method visible everywhere within a package and
subclasses in other packages.
Private
Access:
Private variables and functions are accessible within the class only. They
cannot be inherited in the subclasses so not visible in subclasses.
Private
protected Access:
It makes fields visible in all subclasses of different packages but not visible
to other classes in the same package.
No comments:
Post a Comment