Lab Session 4 - Classes and Objects
Lab Session 4 - Classes and Objects
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the object respectively. fields are
used to store data. methods are used to perform some operations. For our bicycle object, we can create the
class as
class Bicycle {
private int gear = 5;
public void braking() {
System.out.println("Working of Braking");
}
}
In the above example, we have created a class named Bicycle. It contains a field named gear and a
method named braking(). Here, Bicycle is a prototype. Now, we can create any number of bicycles using
the prototype. And, all the bicycles will share the fields and methods of the prototype.
Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of the class.
We have used the new keyword along with the constructor of the class to create an object. Constructors
are similar to methods and have the same name as the class. For example, Bicycle() is the constructor of
the Bicycle class. Here, sportsBicycle and touringBicycle are the names of objects. We can use them to
access fields and methods of the class. As you can see, we have created two objects of the class. We can
create multiple objects of a single class in Java.
Note: Fields and methods of a class are also called members of the class.
// create object
Bicycle sportsBicycle = new Bicycle();
Here, we have created an object of Bicycle named sportsBicycle. We then use the object to access the
field and method of the class.
Now that we understand what is class and object. Let's see a fully working example.
In the above program, we have created a class named Lamp. It contains a variable: isOn and two
methods: turnOn() and turnOff(). Inside the Main class, we have created two objects: led and halogen of
the Lamp class. We then used the objects to call the methods of the class.
led.turnOn() - It sets the isOn variable to true and prints the output.
halogen.turnOff() - It sets the isOn variable to false and prints the output.
The variable isOn defined inside the class is also called an instance variable. It is because when we create
an object of the class, it is called an instance of the class. And, each instance will have its own copy of the
variable. That is, led and halogen objects will have their own copy of the isOn variable.
Example: Create objects inside the same class
Note that in the previous example, we have created objects inside another class and accessed the members
from that class. However, we can also create objects inside the same class.
class Lamp {
// stores the value for light, true if light is on, false if light is off
boolean isOn;
void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);
}
public static void main(String[] args) {
Lamp led = new Lamp();
led.turnOn();
}
}
Output
CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
Light on? True
Here, we are creating the object inside the main() method of the same class.
class JavaExample3{
static int var1;
static String var2;
static void disp(){
System.out.println("Var1 is: "+var1);
System.out.println("Var2 is: "+var2);
}
public static void main(String args[])
{
disp();
}
}
Output
Var1 is: 0
Var2 is: null
Example 2: Static variables are shared among all the instances of class
In this example, String variable is non-static and integer variable is Static. As you can see in the output
that the non-static variable is different for both the objects but the static variable is shared among them,
that’s the reason the changes made to the static variable by object ob2 reflects in both the objects.
class JavaExample{
static int var1=77;
String var2;
public static void main(String args[])
{
JavaExample ob1 = new JavaExample();
JavaExample ob2 = new JavaExample();
CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
ob1.var1=88;
ob1.var2="I'm Object1";
ob2.var1=99;
ob2.var2="I'm Object2";
System.out.println("ob1 integer:"+ob1.var1);
System.out.println("ob1 String:"+ob1.var2);
System.out.println("ob2 integer:"+ob2.var1);
System.out.println("ob2 STring:"+ob2.var2);
}
}
Output
ob1 integer:99
ob1 String:I'm Object1
ob2 integer:99
ob2 STring:I'm Object2
Exercises
1. Write a class Employee having data members to store the following information: Name, Father’s
Name, CNIC, Department, Salary and Designation. Write a method void printInfo() that prints
all information of the employee. Also write a class to test all methods of Employee class.
2. Write a class Box having data members to store the following information: Width, Height and Depth
and method to store the volume of a box using formula (width*height*depth).
Create two objects myBox1 and myBox2 for the above class.
Print values of width, depth and height for each object.
Calculate volume for both objects.
3. Write a class Student having attributes to store the following data: Name, Fathers’ Name,
Department, Degree, Enrolment, Seat number, and Marks of three subjects. Add the following
methods in the above class.
int getTotal() : This methods returns the total of marks
void printTotal() Prints the total marks of Student
float getPercentage() this method calculates the percentage of a student
void printPercentatge() this method prints the percentage of student
char getGrade() this method calculates and returns the grade.
void printGrade() this method prints the grade of a student.
void printInfo() This method prints all information of the student.
Also write a class to test all methods of Student class.
4. Create class SavingsAccount. Use a static variable annualInterestRate (type double) to store the
annual interest rate for all account holders. The class also contains an instance variable
savingsBalance indicating the amount the saver currently has on deposit. Provide method
calculateMonthlyInterest() to calculate the monthly interest by multiplying the savingsBalance by
annualInterestRate divided by 12, this interest should be added to savingsBalance. Provide a static
method modifyInterestRate() that sets the annualInterestRate to a new value.
Write another class TestSavingsAccount that instantiates two savingsAccount objects, saver1 and
saver2, with balances of Rs. 20,000.00/- and Rs. 300,000.00/- respectively. Set annualInterestRate
to 4%, then calculate the monthly interest and print the new balances for both savers. Then set the
annualInterestRate to 5%, calculate the next month’s interest and print the new balances for both
savers.