0% found this document useful (0 votes)
11 views44 pages

CH 07

Chapter 7 introduces Object-Oriented Programming (OOP) concepts, focusing on classes and objects as fundamental components. It explains the importance of classes as blueprints for creating objects, which encapsulate attributes and methods, enhancing code readability, reusability, and maintainability. The chapter also covers the structure of classes, including instance variables, methods, constructors, and the role of driver classes for testing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views44 pages

CH 07

Chapter 7 introduces Object-Oriented Programming (OOP) concepts, focusing on classes and objects as fundamental components. It explains the importance of classes as blueprints for creating objects, which encapsulate attributes and methods, enhancing code readability, reusability, and maintainability. The chapter also covers the structure of classes, including instance variables, methods, constructors, and the role of driver classes for testing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Chapter 7: Introduction to

Classes and Objects

Badour AlBahar
Kuwait University

Slides adopted from:


ENG-200 Java How to Program, 10/e Late Objects Version
Fall 2024
Object-Oriented Programming (OOP)
What is Object-Oriented Programming?
• A programming paradigm where we use objects to solve tasks.

Why?
• Makes programs easier to understand, correct, and modify.
• Allows code reuse, increasing productivity.
A class is a blueprint for An object is an instance of a class.
creating objects.
Object: Student1
Attributes:
Name: Saleh
Major : CpE
Class: Student Year: 2022

Attributes: Methods:
Name Study, AttendClass, takeExam
Major
Year
Object: Student2
Methods:
Study, AttendClass, takeExam Attributes:
Name: Zain
Major: CpE
Year: 2021

Methods:
Study, AttendClass, takeExam
A class is a blueprint for An object is an instance of a class.
creating objects.
Object: Account1
Attributes:
Number: 102961
Balance: 1,513
Class: Bank Account
Methods:
Attributes: Withdraw, Deposit
Number
Balance

Methods: Object: Account2


Withdraw, Deposit
Attributes:
Number: 883923
Balance: 93,192

Methods:
Withdraw, Deposit
Class: Student Class: Bank Account
Attributes: Attributes:
Name Number
Major Balance
Year
Methods:
Methods: Withdraw, Deposit
Study, AttendClass, takeExam

Classes:
• Classes are reusable software components representing real-world
entities.
• Classes have attributes (e.g., name, color, size).
• Classes have methods (e.g., calculating, moving, communicating)
that house program statements to perform certain tasks.
Object: Student1 Object: Account1
Attributes: Attributes:
Name: Saleh Object: Student2 Number: 102961
Major : CpE
Attributes:
Balance: 1,513 Object: Account2
Year: 2022
Name: Zain Methods: Attributes:
Methods: Major: CpE Withdraw, Deposit Number: 883923
Year: 2021
Study, AttendClass, takeExam Balance: 93,192

Methods: Methods:
Study, AttendClass, takeExam Withdraw, Deposit

Objects:
• An object is an instance of a class.
• You can reuse a class many times to build many objects.
• Objects have their own set of attributes.
• Objects can invoke actions derived from their class.
Imagine a class as a cookie cutter, and an object as the cookie
formed when you use that cutter.

• The cutter is a template for


stamping out cookies, the
cookie is what is made each
time the cutter is used
• One template can be used to
make an infinite number of
cookies, each one just like
the other.

Image source
Why Do We Need Classes?
Real-world entities are complex: Often, we need to represent more
complicated data types. For example, when keeping track of a student,
we need to store:
• Name
• ID
• GPA
• Number of credits
• Class year, etc.
Why Do We Need Classes?
A bad approach:
One way to do this is by using multiple arrays to hold this information.
But this approach:
• Is complicated
• Leads to messy, hard-to-read code
• Is difficult to maintain and update over time.
Why Do We Need Classes?
The better approach:
• Create a class to define a new type.
• A class is a blueprint that combines variables (like name, ID, and GPA) and
actions (like calculating a GPA or changing the number of credits) into a single,
easy-to-use unit.
Why Do We Need Classes?
Why classes make life easier:
• Readability: Grouping related information together in one class is much
easier to understand.
• Reusability: Once defined, a class can be reused as many times as needed to
create many students.
• Maintainability: Changing or updating the class design automatically affects
all the instances, making maintenance simpler.
Why Do We Need Classes?
• Each class you create becomes a new type that can be used to declare
variables and create objects.
• You can declare new classes as needed; this is one reason Java is
known as an extensible language.
Main Components of a Class
• Class Declaration:
public class Student {

} // end of class Student

• Every class declaration contains keyword class followed immediately by the


class’s name.
• Each class declaration that begins with the access modifier public must be
stored in a file that has the same name as the class and ends with the .java
filename extension.
• Class names begin with an uppercase letter.
Main Components of a Class
• Instance Variables:
public class Student {

// instance variables
private String name;
private String id;
private double gpa;
private int credits;

} // end of class Student

• Instance variables store an object's attributes (e.g., a student’s name or ID).


• Each object created from the class has its own separate copy of these instance
variables.
• They are created when the object is created and used when methods are called.
• Methods within the class can access and modify instance variables.
© Copyright 1992-2015 by Pearson Education, Inc. All Rights
Reserved.
Main Components of a Class
• Instance Variables:
public class Student {

// instance variables
private String name;
private String id;
private double gpa;
private int credits;

} // end of class Student

Access modifiers: public and private


• Most instance-variable declarations are preceded with the keyword
private, which is an access modifier.
• Variables or methods declared with access modifier private are accessible
only to methods of the class in which they’re declared.
Main Components of a Class
• Instance Variables:
• Every instance variable has a default initial value—provided by Java
• The default value for an instance variable:
• String is null
• byte, char, short, int, long, float and double are initialized to 0
• boolean is initialized to false.
• You can specify your own initial instance variable by assigning the variable a value in
its declaration, as in

private int numberOfStudents = 10;


Main Components of a Class
• Methods:
• Methods are blocks of code that define actions or behaviors for the class.
• They allow us to perform operations on instance variables or handle specific
tasks.

• Local Variables in Methods:


• Variables declared inside a method (including parameters) are called local
variables.
• Local variables can be used only within that method.
Main Components of a Class
• Static vs. Non-static Methods:
Static methods belong to the class Non-static methods (instance
itself and do not require an instance to methods) belong to an object (or
be called. instance) of the class.
• A static method can call other static • Instance methods can access all fields
methods of the same class directly (i.e., (static variables and instance variables) and
using the method name by itself) and can methods of the class.
manipulate static variables in the same
class directly.
• To access the class’s instance variables
and instance methods, a static method
must use a reference to an object of the
class.
Main Components of a Class
• Non-static Methods (instance methods):
• Setters are instance methods that allow us to modify the instance variables.
• In our class Student, a setName method allows us to change the student’s
name:
public void setName(String name){
// Update instance variable 'name'
this.name = name;
}

• Method setName’s declaration indicates that setName receives parameter


name of type String—which represents the name that will be passed to the
method as an argument.
© Copyright 1992-2015 by Pearson Education, Inc. All Rights
Reserved.
Main Components of a Class
• Non-static Methods (instance methods):
• Getters are instance methods that allow us to access the instance variables,
typically without changing them.
• In our class Student, a getName method returns the student’s name:
public String getName(){
// Return the instance variable 'name’
return name;
}

• Since we are just retrieving data, getters usually don’t need any parameters.
Main Components of a Class
• Constructor:
• A constructor is a special method that is called when an object of the class is
created.
• Its purpose is to initialize the object, setting up any necessary data (usually
the instance variables).
• Every time an object is created, Java requires a call to a constructor, whether
it’s a default or custom constructor.
Main Components of a Class
• Custom Constructor:
public class Student {
// instance variables
private String name;
private String id;
private double gpa;
private int credits;

public Student(String name, String id, double gpa, int credits){


this.name = name;
this.id = id;
this.gpa = gpa;
this.credits = credits;
} //end of constructor
} // end of class Student
Main Components of a Class
Constructor Features:
• Custom Constructor: • No Return Type: Constructors do not have a return type,
not even void. This is what differentiates them from
public class Student { regular methods.
// instance variables • Same Name as Class: The name of the constructor must
private String name; match the name of the class exactly.
private String id;
private double gpa;
• Constructors can accept parameters to help initialize
private int credits; instance variables.

public Student(String name, String id, double gpa, int credits){


this.name = name;
this.id = id;
this.gpa = gpa;
this.credits = credits;
} //end of constructor
} // end of class Student
Main Components of a Class
• Default Constructor:
• If you do not explicitly define a constructor, Java will provide a default
constructor with no parameters, and instance variables will be initialized to
their default values.
• If you do explicitly define a constructor, Java will not provide a default
constructor.
Test Class (Driver Class)
• A driver class is a class used to test another class by creating objects
of that class and calling its methods.
• It acts like a "test environment" where we run our code to check if
everything is working as expected.
• A driver class usually contains a main() method that is the starting
point of the program. It does not typically have instance variables or
complex methods—its main job is to test other classes.
Test Class (Driver Class)
• Purpose of a Driver Class:
• Create objects from the class being tested.
• Call methods on those objects to see how the class behaves.
• It helps you verify if the class is functioning correctly, especially after creating
instance variables, methods, or constructors.
Test Class (Driver Class)
public class StudentTest{

public static void main(String[] args){


Student student1 = new Student("Noor","202111111", 3.0, 60);

System.out.printf("The name of the student is %s \n",s1.getName());


s1.setName("Asmaa");
System.out.printf("The name of the student is %s \n",s1.getName());

} //end of main

} // end of class StudentTest


Creating Objects
ClassName objectName = new ClassName(arguments);

• To create an object of a class in Java, we use the new keyword.


• This is called instantiating an object, which means creating a specific
instance of the class.

Student student1 = new Student("Noor","202111111", 3.0, 60);


Creating Objects
ClassName objectName = new ClassName(arguments);

• To create an object of a class in Java, we use the new keyword.


• This is called instantiating an object, which means creating a specific
instance of the class.

Student student1 = new Student("Noor","202111111", 3.0, 60);

This is a call to the constructor of the Student class,


which initializes the object’s variables.
Test Class (Driver Class)
public class StudentTest{

public static void main(String[] args){


Student student1 = new Student("Noor","202111111", 3.0, 60);

System.out.printf(”Student’s name is %s \n", student1.getName());


student1.setName("Asmaa");
System.out.printf("Student’s name is %s \n", student1.getName());

} //end of main

} // end of class StudentTest


Adding a Method: addGrade()
• Goal: We want to create a method called addGrade() that allows us to
add a course letter grade (A, B, C, D, or F) to the student, represented
as a String.
Adding a Method: addGrade()
What Do We Need?
ArrayList<String> to track grades:
• Since we want to store multiple course letter grades (as String) for each
student, we need an ArrayList<String> to hold these grades.

Why Use ArrayList Instead of an Array?


• Dynamic Size: Unlike arrays, ArrayList can grow dynamically, so we don’t need
to know the number of grades in advance.
import java.util.ArrayList;

public class Student {


// instance variables
private String name;
private String id;
private double gpa;
private int credits;
private ArrayList<String> grades; // Stores letter grades as Strings

public Student(String name, String id, double gpa, int credits){


this.name = name;
this.id = id;
this.gpa = gpa;
this.credits = credits;

grades = new ArrayList<String>(); // Initialize ArrayList


} // end of constructor
} // end of class Student
Implementation of addGrade()Method:
public void addGrade(String g){

// Check if the grade is valid (A, B, C, D, or F)


if(g.equals("A") || g.equals("B") || g.equals("C") || g.equals("D") || g.equals("F")){
grades.add(g); // Add the valid grade to the ArrayList

// Update credits after adding the grade


int newCredits = getCredits() + 3; // Assume each course is worth 3 credit
setCredits(newCredits); // Set the new credit count
} else {
System.out.println("Invalid grade. Please enter A, B, C, D, or F.");
}

} // end of method addGrade


Implementation of addGrade()Method:
public void addGrade(String g){

// Check if the grade is valid (A, B, C, D, or F)


if(g.equals("A") || g.equals("B") || g.equals("C") || g.equals("D") || g.equals("F")){
grades.add(g); // Add the valid grade to the ArrayList

String Comparison:
// Update credits after adding the grade
•intDo
newCredits
not use= getCredits()
== to compare+ 3; // Assume
stringseach course is worth 3 credit
in Java.
setCredits(newCredits); // Set the new credit count
} else {
• The == operator compares the memory reference of two strings, not
their actual value.
System.out.println("Invalid This
grade. means
Please enteritA,checks whether
B, C, D, or F."); the strings are the
} same object.
• Use .equals() to compare the values of two strings.
} // end of method addGrade
• The .equals() method compares whether the value of two strings is the
same, not whether they are the same object.v
Method to get the list of grades
public ArrayList<String> getGrades(){
return grades;
}
Test Class (Driver Class): StudentTest
public class StudentTest{

public static void main(String[] args){


Student student1 = new Student("Noor","202111111", 3.0, 60);

System.out.printf(”Student’s name is %s \n", student1.getName());


student1.setName("Asmaa");
System.out.printf("Student’s name is %s \n", student1.getName());

student1.addGrade("A");
student1.addGrade("A");
student1.addGrade("C");
System.out.println("Grades are " + student1.getGrades());

} //end of main

} // end of class StudentTest


Adding a Method: computeGPA()
• Goal: We want to add a method called computeGPA() to the Student
class that calculates the student's GPA based on their grades and
credits.
• GPA Calculation Rule:
• GPA = sum of grades (as points) / number of credits.
• Grade to Points Conversion:
• 'A': 4.0, 'B':3.0, 'C':2.0, 'D':1.0, 'F':0.0
Adding a Method: computeGPA()
Steps:
• Loop through the grades list.
• For each grade, convert it to points.
• Add the points to the total sum.
• Divide the sum by the total credits to compute the GPA.
public void computeGPA(){

double sum = 0; // Sum of grade points

for (String g : grades) {


sum += changeLetter(g); // Convert letter grade to points and add to sum
}

setGpa(sum / getCredits()); // Calculate GPA by dividing sum of points by total credits


}

// Method to change letter grade to points


public double changeLetter(String g) {
if (g.equals("A"))
return 4.0;
else if (g.equals("B"))
return 3.0;
else if (g.equals("C"))
return 2.0;
else if (g.equals("D"))
return 1.0;
else if (g.equals("F"))
return 0.0;
return 0.0; // Default case
}
Exercise
Create a BankAccount class with the following:
• Instance Variables:
• accountHolder (String)
• balance (double)
• accountNumber (String)
• A constructor to initialize all fields.
• Setters and getters for the fields.
• Methods:
• deposit(double amount): Adds money to the balance.
• withdraw(double amount): Deducts money from the balance if
sufficient funds are available.
• checkBalance(): Returns the current balance.
Shape Classes
Exercise
You will design and implement classes for two geometric shapes: Circle
and Rectangle. Each class will include instance variables, a constructor
to initialize them, and methods to compute their area and perimeter.
• Circle Class
• Instance variable: radius (double).
• Constructor: Accepts the radius and initializes it.
• Implement the methods:
• getArea(): Returns the area of the circle.
• getPerimeter(): Returns the perimeter of the circle.
• Rectangle Class
• Instance variables: length and width (both double).
• Constructor: Accepts the length and width and initializes them.
• Implement the methods:
• getArea(): Returns the area of the rectangle.
• getPerimeter(): Returns the perimeter of the rectangle.

You might also like