Escolar Documentos
Profissional Documentos
Cultura Documentos
Module I
Classes, Objects, and Methods
MICROHARD
Overloaded methods and Constructors
Returning objects.
Recursion
Access Control.
Class fundamentals
Classes are the fundamental units of design in Object-Oriented Programming. Consider
an example that defines a type to represent the career profile of a batsman which
consists of say , number of matches played, total runs scored and average. We need
three integer (or float) spaces in memory. We want to make it a single entity. In Java
this is done as follows:
MICROHARD
float average;
}
Therefore, now we have a new data type called Batsman. Wherein we have aggregated
three basic data types. This is not all, you can add some methods to the above
definition, say to calculate the new average or to retrieve the information and display it.
Call these methods as calcAvg( ), getData( ). ShowResult( ) The above definition would
change to:
MICROHARD
body of the method;
}
-
-
.
}
A class is declared by using the keyword class. The data or variables within a class are
called as instance variables. Methods defined shall operate on the instance variables.
A simple class: The notion classes and objects will be clear with the following
illustration.
class Point
{
int x;
int y;
}
Point is the new data type, which consists of two member variables x and y that
represents the coordinates of a point. Just like any other data type and variable, we can
have a variable of type Point and this variable is nothing but your object.
The above statement actually consists of three parts – the declaration, creation and
assignment.
This would allocate memory for the reference. (C / C++ programmers can think of
reference as pointers)
pt1 XXXX
MICROHARD
X 0
Y 0
At this point, the reference variables (pt1) refer to the actually created object.
Pt1 Address x 0
y 0
Every Point object will contain its own copy of variables x and y as shown in the above
discussion. We can define classes and objects as:
Class
A class is a blue print for objects. It defines the object according to the data and the
operations that the object can perform.
Object
It is a programming unit that combines data and methods to manipulate data.
Now, how do we access the individual members of the object ? This is achieved using
the dot (.) operator. The dot operator links the object name and the member of the
object.
For Example, if you want to assign 50 and 100 as the values for x and y of the object
pt1,
pt1.x = 50;
pt1.y = 100;
MICROHARD
Similarly for pt2
pt2.x = 100;
pt2.y = 200;
Here is the complete listing of the above explanation.
Listing 3.1
class Point
{
int x;
int y;
MICROHARD
y First Statement
pt2
Second Statement
Methods
As mentioned in the previous section, a class would contain both methods and
variables. The general form of any method is
Class Point ( )
{
int x;
int y;
void showCoordinates ( )
{
System.out.println(“x= “+x + “ and y=” +y);
}
}
Again, if pt1 is your object, a call to the method can be made using the dot operator.
pt1.showCoordinates ( );
MICROHARD
The complete program is shown below.
Listing 3.2
class MethodDemo
{
int x=5;
int y=10;
void getCoordinates( )
{
System.out.println(" X= " +x + " , Y= "+y);
}
public static void main(String args[ ])
{
MethodDemo start=new MethodDemo( );
start.getCoordinates( );
}
}
int square(int a)
{
return a*a;
}
A call to this method would be
int x = square(10);
10 is passed into the parameter ‘a’ and the value returned by the function square is
assigned to x.
Listing 3.3
class ParameterDemo
{
void getCoordinates(int x,int y)
{
System.out.println(" X= " +x + " , Y= "+y);
System.out.println( );
}
MICROHARD
public static void main(String args[ ])
{
ParameterDemo start=new ParameterDemo( );
start.getCoordinates(10,20);
start.getCoordinates(30,40);
start.getCoordinates(50,60);
}
}
Constructors
Constructors are special member functions that are used to initialize the instance
variable at the time when the object is created. The constructor method would have the
same name as that of class. There are three types of constructors:
2. Parameterized constructors.
Constructor rules
1. Constructors cannot have return type. Not even void.
Listing 3.4
class Customer
{
String name;
String acc_no;
double bal;
Customer( )
{
name=”xyz”;
acc_no=”123”;
bal=0;
}
MICROHARD
Customer(String n,String a,double b)
{
name=n;
acc_no=a;
bal=b;
}
void showBalance()
{
System.out.println("Name : "+name);
System.out.println("Balance : "+bal);
System.out.println();
}
}
class BankDemo
{
public static void main(String args[ ])
{
Customer cust[ ]=new Customer[4];
cust[0]=new Customer("venky","abc11",5673.56);
cust[1]=new Customer("siri","abc09",7658.45);
cust[2]=new Customer("debu","abc10",6457.00);
cust[3]=new Customer( );
for(int i=0;i<4;i++)
{
cust[i].showBalance();
}
}
}
Example:
Point (int x, int y)
{
this.a=x;
this.b=y;
}
Overloading methods
MICROHARD
Method overloading is one of the ways, in which Java implements polymorphism,
which is one of the exiting features of Object-Oriented Programming.
Method overloading is the process of having two or more separate methods in the same
class that share the same name, which vary in their parameter list and declarations.
Method overloading allows you to group conceptually similar methods under the same
name and to use simpler name in general. Consider the following example:
All the above methods are overloaded. Without method overloading, each max()
method would have had different names say maxInt, maxFloat and so on. Using the
same name is simpler and conveys the unity of purpose among these four methods.
Listing 3.5
class OverLoadingDemo
{
void cube(int i)
{
System.out.println("this is an integer version");
System.out.println("The cube of "+i+ " is " + (i*i*i));
}
void cube(float i)
{
System.out.println("this is an float version");
System.out.println("The cube of "+i+ " is " + (i*i*i));
}
void cube(double i)
{
MICROHARD
System.out.println("this is an double version");
System.out.println("The cube of "+i+ " is " + (i*i*i));
}
void cube(long i)
{
System.out.println("this is an long version");
System.out.println("The cube of "+i+ " is " + (i*i*i));
}
public static void main(String args[])
{
OverLoadingDemo obj=new OverLoadingDemo();
obj.cube(5);
obj.cube(5.09);
obj.cube(5.09F);
obj.cube(9L);
}
}
Overloading constructors
Overloading constructors is same as overloading methods. This is illustrated in the
following example.
Listing 3.6
class ConstructorDemo
{
int x;
int y;
ConstructorDemo( )
{
x=0;
y=0;
}
ConstructorDemo(int a, int b)
{
x=a;
y=b;
}
void getCoordinates( )
{
System.out.println(" X= " +x + " , Y= "+y);
System.out.println();
}
MICROHARD
{
ConstructorDemo start=new ConstructorDemo( );
ConstructorDemo end=new ConstructorDemo(20,20);
start.getCoordinates( );
end.getCoordinates( );
}
}
Argument passing
It is possible to send and receive objects in the same way as it is done using basic data
types. This is illustrated in the following listing.
Copy Constructors
One of the most common uses of passing objects as arguments involves constructors. If
you want to initialize an object using an already existing object, the simple solution is to
pass the parameter. Look at the following example.
Listing 3.7
class Complex
{
int x,y;
Complex()
{
x=y=0;
}
Complex(int a,int b)
{
x=a;
y=b;
}
Complex(Complex obj)
MICROHARD
{
x=obj.x;
y=obj.y;
}
void show()
{
System.out.println("The complex representation of "+x+" and " +y+" is "+x+"+j"+y);
}
public static void main(String args[])
{
Complex c1=new Complex();
Complex c2=new Complex(10,20);
Complex c3=new Complex(c1);
Complex c4=new Complex(c2);
c1.show();
c2.show();
c3.show();
c4.show();
}
}
Such constructors that accept object as parameters are called as copy constructors
because the new object is copied from the existing one.
1. Pass by value
2. Pass by reference
In the first method, values passed are simply copied into the formal parameter of the
method. Therefore, any changes made to the parameter will not have any effect on the
actual parameter.
In the second method, references are used to access the actual argument specified in the
formal argument given in the call. Therefore, any changes made to the parameter (the
formal argument) will affect the argument (actual argument) method in the call.
In Java, passing simple data types to methods ,is done by ‘pass by value’ method.
When you pass objects as arguments, it will be pass by reference because you are
actually working with the original copy.
MICROHARD
A method can return objects in the same way as they can accept it. The object being
returned should be accepted by another object of the same type. Here is the example to
show the same.
Listing 3.9
class Time
{
int hours;
int minutes;
int seconds;
void showTime()
{
MICROHARD
Access Specifiers
This is concerned with the visibility of a variable or a method. If a variable or method is
visible in another class, then the objects of their class can refer to the members
belonging to the other class. This can be restricted too, if needed. All these and more
can be achieved using the four access specifiers or visibility modes available in Java.
Public
Members with access specifier as public are available to any class. This is the widest
possibility of visibility.
Private
Members can be accessed only within the class where it is declared. Further more, the
private variables are accessible only within the member functions of that class. Hence,
it provides the highest level of security and aids in data hiding.
The other two specifiers, package and protected are discussed later.
Recursive methods
The method by which a function calls itself is known as recursion. Though, recursion
helps in reducing the code, care should be taken not to allow it to go to infinity and thus
cause stack overflow problems.