Você está na página 1de 15

Module I Classes, Objects, and Methods 1

Module I
Classes, Objects, and Methods

In this module, you will learn….


 Class Fundamentals.
 Declaring objects.
 Methods
 Constructors
 The this keyword.

MICROHARD
 Overloaded methods and Constructors
 Returning objects.
 Recursion
 Access Control.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 2

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:

public class Batsman


{
int matches;
int runs;

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:

public class Batsman


{
int matches;
int runs;
float average;
public void calcAvg( )
{
body;
}
public void getData( )
{
body;
}
public void showResult ( )
{
body;
}
}

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 3

The general form of the class definition is shown below


class classname
{
type instance - reliable 1;
type instance – reliable 2;
.
.
.
type methodname1 (parameter list)
{
body of the method;
}

type methodname2 (parameter list)


{

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.

To create a Point object, the following statement is used:

Point pt1 = new Point( );

The above statement actually consists of three parts – the declaration, creation and
assignment.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 4

Declaration: Point pt1;

This would allocate memory for the reference. (C / C++ programmers can think of
reference as pointers)

pt1 XXXX

Creation: new Point ( );

Pt 1 XXXX this initializes storage

MICROHARD
X 0
Y 0

Assignment: pt1 = new Point ( );

At this point, the reference variables (pt1) refer to the actually created object.

Pt1 Address x 0
y 0

Similarly, we can create as many object references to the class Point.

Point pt2 = new Point ( );

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.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 5

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;

public static void main(String args[])


{
Point start=new Point( );
Point end=new Point( );
start.x=10;
start.y=10;
end.x=20;
end.y=30;
System.out.println("Start point : X= " +start.x + " , Y= "+start.y);
System.out.println(" End point : X= " +end.x + " , Y= "+end.y);
}
}

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 6

Now what happens if you have the statements like this,

Point pt1 = new Point ( );


Point pt2 = pt1;
The second statement does not create another separate location for the instance
variables x and y. Instead it would point to the same variables belonging to that of pt1.
This is nothing but the assignment of reference variables and can be shown as follows.

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

return type methodname (parameter list)


{
body of the method
return value;
}
Continuing with the same example of class Point if you want to add a method called
showCoordinates ( ), the class definition would change to:

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 7

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

Methods with parameters


Parameterized methods allow the program to be generalized. For example Consider the
following code

int square(int a)
{
return a*a;
}
A call to this method would be

int x = square(10);

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 8

10 is passed into the parameter ‘a’ and the value returned by the function square is
assigned to x.

A class with parameterized method is shown below

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:

1. Non – parameterized constructors.(default constructors)

2. Parameterized constructors.

3. Copy constructors (see next section).

Constructor rules
1. Constructors cannot have return type. Not even void.

2. Constructors should always be public members.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 9

A example showing default and parameterized constructors

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

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 10

The ‘this’ keyword


‘this’ is the keyword that is used to refer the object that invoked a method. Using this
inside any method would refer to the current object that invoked the method.

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:

max (int, int) –method max with integer parameter


max (float, float) – method max with float type parameter
max (double, double) – method max with double type parameter
max (long, long) – method max with long type parameter

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.

Here is a simple example that illustrates method overloading.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 11

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;

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 12

y=0;
}

ConstructorDemo(int a, int b)
{
x=a;
y=b;
}

void getCoordinates( )
{
System.out.println(" X= " +x + " , Y= "+y);
System.out.println();
}

public static void main(String args[ ])

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.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 13

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.

Argument passing techniques


There are two ways of passing arguments:

1. Pass by value

2. Pass by reference

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 14

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 getTime(int h,int m,int s)


{
hours=h;
minutes=m;
seconds=s;
}

void findSum(Time t1,Time t2)


{
seconds=t1.seconds+t2.seconds;
minutes=seconds/60;
seconds=minutes%60;
minutes=minutes+t1.minutes+t2.minutes;
hours=minutes/60;
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}

void showTime()
{

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited
Module I Classes, Objects, and Methods 15

System.out.print("The total time is " +hours+ " Hours ");


System.out.println(""+minutes+" Minutes and "+seconds+" Seconds");
}
public static void main(String args[])
{
Time t1=new Time();
Time t2=new Time();
Time t3=new Time();
t1.getTime(5,67,200);
t2.getTime(6,75,60);
t3.findSum(t1,t2);
t1.showTime();
t2.showTime();
t3.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.

Prepared by Microhard Institute of Technology


Training Material for i - flex Solutions Limited

Você também pode gostar