Lab 5
Lab 5
Topic Covered:
Class and Object, Defining class, Instance Variables, Declaring Objects, Assigning Object Reference Variables,
Methods, calling methods, Constructor, The this Keyword, Math Class, The String Class
In Java, classes are composed of data and operations—or functions (methods)—that operate on the data. Objects
of a class are created using the class as a template, or guide. Think of the class as a generic description, and an
object as a specific item of that class. The identifier of the object is called the object reference. Creating an object
of a class is called instantiating an object, and the object is called an instance of the class.
The data associated with an object of a class are called instance variables, or fields, and can be variables and
constants of any primitive data type (byte, short, int, long, float, double, char, and boolean), or they can be objects
of a class.
The operations for a class, called methods, set the values of the data, retrieve the current values of the data, and
perform other class-related functions on the data. Invoking a method on an object is called calling the method.
In a well-designed class, only the class methods can change the data. Methods of other classes cannot directly
access the data. We say that the data are private to the class.
DEFINING CLASS
INSTANCE VARIABLES
Instance variable of a class hold the data for each object of that class. Instance variable are properties of the objects.
Each object will get its own copy of the instance variable each of which be given a value appropriate to that object.
Instance variable may be defined with private access modifiers so that only methods the class can set or change
the value of instance variables. In this way we achieve the encapsulation the class provides a protective shell
around the data. Data type of an instance variable can be any of java’s primitive data types or class types.
PROGRAM 1: A program that uses the Box class. To run Program save this file “BoxDemo.java”
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
DECLARING OBJECTS
Instantiating an object consists of defining an object reference—which will hold the address of the object in
memory—and calling a special method of the class called a constructor, which has the same name as the class.
The job of the constructor is to assign initial values to the data of the class. Syntax for declaring an object
reference:
ClassName objectReference;
objectReference = new ClassName(argument list);
Example:
Box mybox;
Declares mybox as a reference to an object of type Box. After this line executes, mybox contains the value null
Object reference variables act differently than you might expect when an assignment takes place. For example:
The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer
to the same object as does b1.
METHODS
Methods provide a functions for the class, typically method names are verbs. Access modifier for methods that
provide services to the clients will be public. Methods that provide services only to other methods of the class are
typically declared to be private. Return type of a method is the data type of the value that the method returns to
the caller. All objects of the class shares one copy of the class methods. If function returns the value it must contain
return statement in its body.
Methods that have a return type other than void return a value to the calling routine usingthe following form of
the return statement:
return value;
CALLING METHODS
Once an object is instantiated, we can use the object by calling its methods. To call a method for an object of a
class, we use dot notation, as follows:
objectReference.methodName(argument list);
If you attempt to call a method using an object reference whose value is null, Java generates either a compiler error
or a run-time error called NullPointerException.
PROGRAM 2: This program includes a method inside the box class. Save this file “BoxDemo2.java”
class Box {
double width;
double height;
double depth;
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
PROGRAM 3: This program uses a parameterized method. Save this file “BoxDemo3.java”
class Box {
double width;
double height;
double depth;
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volumes
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
CONSTRUCTOR
Constructor is s special method that is called when an object is instantiated using the new keyboard. A class can
have several constructors. The jobs of the constructor is to initialize the variables of the objects. Constructor has
the same name as the class and has no return type not even void. Important to use public access modifier for
constructor so that application can instantiate the objects of the class. Constructor can either assign default values
to the instance variable or the constructor can accept initial values from the client through parameters when the
object is created. If you don’t write constructor the compiler provides a default constructor which is a constructor
that takes no arguments. This default constructor assign default initial value to the variable like int variable is be
set with default value of 0, double and float with 0.0 boolean with false and char with space and object reference
with null
The syntax for a constructor follows:
class Box {
double width;
double height;
double depth;
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volumes
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
PROGRAM 5: Here, Box uses a parameterized constructor to initialize the dimensions of a box.
class Box {
double width;
double height;
double depth;
class BoxDemo {
public static void main(String args[]) {
double vol;
PROGRAM 6:
class SimpleDate {
int day;
int month;
int year;
SimpleDate() {
day = 1;
month = 1;
year = 1990;
}
void setDay(int d) {
if(d <= 0) {
System.out.println("Day Cannot be set to Zero");
day = 1;
}
else day = d;
}
void setMonth(int m) {
if(m <= 0) {
System.out.println("Month Cannot be set to Zero");
month = 1;
}
else month = m;
}
void setYear(int y) {
if(y <= 0) {
System.out.println("Year Cannot be set to Zero");
year = 1;
}
else year = y;
}
String printDate() {
return day+"/"+month+"/"+year;
}
class DateClient {
public static void main(String[] args) {
SimpleDate bday = new SimpleDate();
System.out.println(bday.printDate());
bday.setDay(10);
bday.setMonth(7);
bday.setYear(1982);
System.out.println(bday.printDate());
bday.nextDay();
System.out.println(bday.printDate());
}
}
MATH CLASS
The Math class is also part of the java.lang package. The Math class provides static constants PI and E (the base of
the natural logarithm, i.e., log e = 1)and static methods to perform common mathematical calculations, such as
finding the maximum or minimum of two numbers, rounding values, and raising a number to a power.
PROGRAM 7:
public class MathConstants
{
public static void main( String[] args )
{
System.out.println( "The value of e is " + Math.E );
System.out.println( "The value of pi is " + Math.PI );
double d3 = Math.log( 5 );
System.out.println( "\nThe log of 5 is " + d2 );
double d4 = Math.sqrt( 9 );
System.out.println( "\nThe square root of 9 is " + d4 );
}
}
The String class can be used to create objects consisting of a sequence of characters. String constructors accept
String literals, String objects, or no argument, which creates an empty String. The length method returns the
number of characters in the String object. The toUpperCase and toLowerCase methods return a String in upper or
lower case. The charAt method extracts a character from a String, while the substring method extracts a String
from a String. The indexOf method searches a String for a character or substring.
PROGRAM 8:
EXERCISE 1:
Write a class encapsulating the concept of a course grade, assuming a course grade has the following
attributes:
course name
letter grade.
Include a constructor, and include the following methods:
A method to take input in course name and grade (restrict user to give wrong values of grade correct
grade value will be: “A, B, C, D and F”)
A method to display course name and grade.
Finally write a client class to test all the methods in your class.