CSL-210: Object-Oriented Programming
Lab
BS(IT)- Semester 02)
Lab: Engr. Saba
Lab05: Classes and Objects
Designing and implementing Java programs that deal with:
1. A class Definition
2. Constroctor
3. Class members
4. Class methods
5. The new Operator to create a new object
6. The this Operator
1. Creating a Class
Type-in the following class in netbeans project. Compile and run this program.
/*
* Creat the Student Class with attributes, methods and Constructors
*/
public class Student {
String name = "Tariq"; // Student's name
int ID = 123; // unique ID number for the student
public Student() {} //default constructor(empty)
public Student(String theName, int theID){
name = theName;
ID = theID;
}
public void printInfo(){
System.out.println("Student Name : "+name);
System.out.println("Student ID : " +ID);
}
} // end of class Student
Constructor:
Constructor is a special class method used to
create a properly initialized instance of the
class.
Constructor must have the same name as the
class itself, which is defined.
Constructors also must have no defined return
value, or type of void.
The purpose is to create an instance to
initialize the value of its members to
default values.
Compile:
Compile the above program and try to Run.
o You will see the following error message.
o <no main class found>
29/86
o Now add this code segment into the Student class.
public static void main(String [] args){
Student std1 = new Student();
Student std2 = new Student("Fahim", 456);
std1.printInfo();
std2.printInfo();
}
new:
The keyword new is used to create the object of
a class.
You are expected to:
Create five (5) more objects and pass different values to constructor and display the output.
2. Creating an Application class and a set of objects
Type-in the following class in the same netbeans project. Compile and run this program.
/*
* Creat the MyApplcation Class to create the objects of Student class
*/
public class MyApplication {
public static void main(String [] args){
Student std1 = new Student();
Student std2 = new Student("Fahim", 456);
std1.printInfo();
std2.printInfo();
}
}
Delete the main method:
After creating this class delete the main method from Student class.
Compiling the Source File:
To compile your source file, choose Build > Build Main Project (F11) from the IDE's main menu.
You can view the output of the build process by choosing Window > Output > Output.
The Output window opens and displays output similar to what you see in the following figure.
You are expected to:
Add the following methods to set (Mutator) and get (Accessor) the values of name and ID attributes in
Student class.
public void setName(String theName) { name =
theName;
}
public void setID(int theID) { ID =
theID;
}
public String gettName( ) { return
name ;
}
public int getID( ) {
30/86
return ID;
}
Use Scanner class object to get input from user and then assign these values to Student class attributes
in MyApplication class.
this:
If the attribute in method header has the
same name as the class attribute then use
this keyword with class attribute.
This example shows the use of keyword this with class attribute.
public public void setName(String name) {
this.name = name;
}
3. Example
Write a class named Car that has the following data members:
yearModel – an int field that hold the car’s year model.
make – a String field that holds the make of the car.
speed – an int field that holds the car’s current speed.
The class also should have the following constructor and other methods:
constructor – that accepts the car’s year model and make as arguments. These values should be
assigned to the object’s yearModel and make fields. The constructor also should assign 0 to the
speed field.
Accessors. Appropriate accessor methods should get the values stored in an object’s yearModel, make
and speed fields.
accelerate. The accelerate method should add 5 to the speed field each time it is called.
brake. The brake method should subtract 5 from the speed field each time it is called.
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make){
this.yearModel = yearModel;
this.make = make;
speed =0;
}
public int getYearModel(){ return yearModel;}
public String getMake(){ return make;}
public int getSpeed(){ return speed;}
public void accelerate(){ speed+=5;}
public void brake(){ speed-=5;}
} // end of class Car
Demonstrate the class in a program that creates a Car object, and then calls the accelerate method five times.
After each call to the accelerate method, get the current speed of the car and display it. Then call the brake
method five times. After each call to the brake method, get the current speed of the car and display it.
31/86
public class CarTest {
public static void main(String [] args){
Car car = new Car(2005,"Volvo");
for(int i=1; i<=5;i++){
car.accelerate();
System.out.println("The speed of car is " + car.getSpeed()+
"kms");
}
for(int i=1; i<=5;i++){
car.brake();
System.out.println("The speed of car is " + car.getSpeed()+
"kms");
}
}// end main
} // end of class CarTest
4. Example
Implement a Student class with the following fields, constructors and methods:
Fields (All should be private):
studentName;
totalScore;
numOfQuizzes
;
Constructor:
public Student(String name)
Methods:
public String getName()
//The following method should return zero if no quiz has been taken.
public double getTotalScore()
public double getAverage()
public void addQuiz(double score)
// The following method should print the student’s name and average
score public String toString()
public class Student{
private String studentName;
private double totalScore;
private int numberOfQuizzes;
public Student(String studentName){
this.studentName = studentName;
totalScore = 0;
numberOfQuizzes = 0;
}
public String getName(){ return studentName;}
public void addQuiz(double score){
totalScore += score;
numberOfQuizzes++;
32/86
}
public double getTotalScore() {return totalScore;}
public double getAverageScore() {
return totalScore/numberOfQuizzes;
}
public String toString(){
return ("Student Name :" +getName()+"\nAverage Score :
" + getAverageScore());
}
}
Write an application StudentTest that reads a student name and use the Student class to create a Student
object. Then read the scores of the student in 3 quizzes and add each to the totalScore of the student using the
addQuiz method, then print the student object.
public class StudentTester {
public static void main(String[] args){
Student student= new Student("Ali");
Scanner input = new Scanner(System.in);
for(int i=1; i<=3;i++){
System.out.println("Enter Quiz " + i + " Score for " +
student.getName()+" :");
int score = input.nextInt();
student.addQuiz(score);
}
System.out.println(student);
}
}
33/86
Exercises
Exercise 1 (Computer Specifications)
Imagine you're setting up a new computer for your office. You want to create a program to input the
details of the computer system, like its name, type, processor specification, RAM, hard disk drives,
motherboard, and optical drive. Write a java program to collect this information from the user and
display it back. Also, user should be able to update any of these details if needed?.
(Hint: Use the concept of constructors and methods.)
Sample Output:
Exercise 2 (Scheduling)
Think about running a scheduling app where you need to record the current date and time for
various tasks and appointments. Write a java program to handle different scenarios, such as creating
default date and time, setting specific dates and times, and allowing updates to these values. The
program must incorporate several Methods out of which three Methods should be constructors, the
first one shall be a default constructor, the second and third one shall be an overloaded constructors,
from which one method deals with YEAR, MONTH AND DAY, whereas the second method deals
34/86
with YEAR, MONTH,DAY,HOUR,MINUTES AND SECONDS. The other methods may include
the set methods and get methods which sets and gets the described values.
Sample Output:
Exercise 3 (Bookstore Inventory)
Consider you're managing a bookstore and need to keep track of the inventory. You want to create a Java class to
represent books, including their titles, authors, and prices. Write a java program having this class to ensure it can
be easily used to create and manage book objects by incorporating with following features:
Instance variables :
o title for the title of book of type String.
o author for the author’s name of type String.
o price for the book price of type double.
Constructor:
o public Book (String title, Author name, double price): A constructor with
parameters, it creates the Author object by setting the the fields to the passed
values.
Instance methods:
o public void setTitle(String title): Used to set the title of book.
o public void setAuthor(String author): Used to set the name of author of book.
o public void setPrice(double price): Used to set the price of book.
o public double getTitle(): This method returns the title of book.
o public double getAuthor(): This method returns the author’s name of book.
o public String toString(): This method printed out book’s details to the screen
Write a separate class BookDemo with a main() method creates a Book titled “Developing Java Software”
with authors Russel Winderand price 79.75. Prints the Book’s string representation to standard output (using
System.out.println).
Sample Output:
35/86