Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

CSC 1042

Programming Fundamentals
BS(CS) 2021
Department of CS and SE

Lab Session 4: Classes and Objects


Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the class. We can
think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors,
windows, etc. Based on these descriptions we build the house. House is the object. Since many houses
can be made from the same description, we can create many objects from a class.

Create a class in Java

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.

Creating an Object in Java

Here is how we can create an object of a class.

className object = new className();


CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
Bicycle sportsBicycle = new Bicycle();
Bicycle touringBicycle = new Bicycle();

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.

Access Members and Methods of a Class


We can use the name of objects along with the . operator to access members of a class. For example,
class Bicycle {
int gear = 5;
void braking() {
...
}
}

// create object
Bicycle sportsBicycle = new Bicycle();

// access field and method


sportsBicycle.gear;
sportsBicycle.braking();

Notice the statement,

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.

sportsBicycle.gear - access the field gear


portsBicycle.braking() - access the method braking()

Now that we understand what is class and object. Let's see a fully working example.

Example: Java Class and Objects


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);
CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
}
void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}
class Main {
public static void main(String[] args) {
Lamp led = new Lamp();
Lamp halogen = new Lamp();
led.turnOn();
halogen.turnOff();
}
}
Output
Light on? true
Light on? False

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.

Java Static Variables


A static variable is common to all the instances (or objects) of the class because it is a class level variable.
In other words, you can say that only a single copy of static variable is created and shared among all the
instances of the class. Memory allocation for such variables only happens once when the class is loaded in
the memory.

Few Important Points:


Static variables are also known as Class Variables. Unlike non-static variables, such variables can be
accessed directly in static and non-static methods.

Example 1: Static variables can be accessed directly in Static method


Here we have a static method disp() and two static variables var1 and var2. Both the variables are
accessed directly in the static method.

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

Java Static Methods


Static Methods can access class variables (static variables) without using object(instance) of the class,
however non-static methods and non-static variables can only be accessed using objects.
Static methods can be accessed directly in static and non-static methods. Static keyword followed by
return type, followed by method name.

static return_type method_name();


Example 1: static method main is accessing static variables without object
class JavaExample{
static int i = 10;
static String s = "Beginnersbook";
public static void main(String args[])
{
System.out.println("i:"+i);
System.out.println("s:"+s);
}
}
Output
i:10
s:Beginnersbook

Example 2: Static method accessed directly in static and non-static method


class JavaExample{
static int i = 100;
static String s = "Beginnersbook";
static void display()
{
System.out.println("i:"+i);
CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
System.out.println("i:"+s);
}
void funcn()
{
//Static method called in non-static method
display();
}
//static method
public static void main(String args[])
{
JavaExample obj = new JavaExample();
//You need to have object to call this non-static method
obj.funcn();
display();
}
}
Output
i:100
i:Beginnersbook
i:100
i:Beginnersbook
CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE

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.

Add more methods in SavingsAccount class if needed.


CSC 1042
Programming Fundamentals
BS(CS) 2021
Department of CS and SE
5. Consider the following class:

public class SomethingIsWrong {


public static void main(String[] args) {
Rectangle myRect;
myRect.width = 40;
myRect.height = 50;
System.out.println("myRect's area is " + myRect.area());
}
}

a. Identify the error in the above class and discuss.


b. Suggest the fix of error identified in part a, and write its corrected version.

You might also like