Lab 3 Manual
Lab 3 Manual
(CS 29008)
The class is at the core of Java. It forms the basis for object-oriented pro-
gramming in Java. Any concept we wish to implement in a Java program
must be encapsulated within a class.
A class is declared by use of the class keyword. A simplified general form
of a class definition is shown below:
Listing 3.1: class syntax
class classname {
dtype v a r i a b l e 1 ;
dtype v a r i a b l e 2 ;
// . . .
dtype v a r i a b l e N ;
17
ables defined within a class are called members of the class. As a general
rule, it is the methods that determine how a class data can be used.
Note that the general form of a class does not specify a main() method.
Java classes do not need to have a main() method. We only specify one if
that class is the starting point for the program. Further, some kinds of Java
applications, such as applets, do not require a main() method at all.
18
public s t a t i c void main ( S t r i n g a r g s [ ] ) {
Box mybox = new Box ( ) ;
double v o l ;
// a s s i g n v a l u e s t o mybox ’ s i n s t a n c e −v a r i a b l e s
mybox . width = 1 0 ;
mybox . h e i g h t = 2 0 ;
mybox . depth = 1 5 ;
19
3.3 Methods
Typically, a class consists of two things: instance-variables and methods.
The general form of a method is:
dtype methodname ( parameter− l i s t ) {
// body o f t h e method
}
Here, dtype refers the type of data returned by the method. The return
type can be any valid built-in data type or a user-defined class type.
Listing 3.3: Adding methods to Box class
c l a s s Box {
double width ;
double h e i g h t ;
double depth ;
// a s s i g n v a l u e s t o mybox ’ s i n s t a n c e −v a r i a b l e s
mybox . width = 1 0 ;
mybox . h e i g h t = 2 0 ;
mybox . depth = 1 5 ;
// g e t volume o f box
v o l = mybox . volume ( ) ;
System . out . p r i n t l n ( ”Volume : ” + v o l ) ;
}
}
Several methods need parameters. The example code shown below illus-
trates the use of parameterized methods.
Listing 3.4: Parameterized methods in class Box
c l a s s Box {
20
double width ;
double h e i g h t ;
double depth ;
// s e t s d i m e n s i o n s o f Box
void setDim ( double w, double h , double d ) {
width = w;
height = h ;
depth = d ;
}
}
c l a s s BoxDemo {
public s t a t i c void main ( S t r i n g a r g s [ ] ) {
Box mybox = new Box ( ) ;
double v o l ;
// i n i t i a l i z e mybox
mybox . setDim ( 1 0 , 2 0 , 1 5 ) ;
// g e t volume o f box
v o l = mybox . volume ( ) ;
System . out . p r i n t l n ( ”Volume : ” + v o l ) ;
}
}
21
22
3.5 Lab 3 Exercises
Objectives:
Outcomes:
• After completing this, the students would be able to develop Java pro-
grams using class, objects and methods.
Lab Assignments
3. set values to two objects using parameterized methods and get the
volumes of two boxes
23