Ch. 2 Object Oriented Concepts
2.1 Defining
User-Defined Classes
Introduction
In the real world, we
deal with "objects" every day: a car, a dog, a smartphone, a book.
Each of these objects has characteristics (such as color,
size, or model) and can perform actions (such as moving, barking, or displaying
information). In Object-Oriented
Programming (OOP), we model these real-world objects in
software.
A class in Java serves as
a blueprint or template for creating objects. It does not represent a specific
object but defines the common properties (data/attributes) and behaviors (methods/functions) that all objects of that type
possess. Once a class is defined, you can create multiple instances (objects) from
that blueprint, each with its own unique attribute values.
Explanation
A class in Java is a
user-defined data type that encapsulates fields
(variables) and methods
(functions) together as a single unit.
·
Blueprint: Just as an architectural blueprint defines the design of a
house (number of rooms, structure, etc.) without being an actual house, a class
defines the structure of an object.
·
Object: The actual house built from that blueprint is an object.
Multiple houses (objects) can be built from one blueprint (class), each with
unique details.
Each object has its own
copy of the attributes defined in the class (unless declared static
), and they share the methods to perform actions on their
specific data.
Key Components of a
Class
·
Fields
(Attributes/Instance Variables):
Variables declared within a class that define the characteristics or state of
an object.
·
Methods: Functions or procedures that define the behaviors or actions an object can perform.
Syntax for Defining a Class
// Syntax for Defining a Class
[access_modifier] class ClassName {
// Fields (Variables or Attributes)
dataType fieldName1;
dataType fieldName2;
// ... add more fields as needed
// Methods (Functions or Behaviors)
[access_modifier] returnType methodName1([parameters]) {
// Code to perform a task
}
[access_modifier] returnType methodName2([parameters]) {
// Code to perform another task
}
// You can add more methods as required
}
·
access_modifier: Controls the
visibility (e.g., public
, private
, protected
, or default).
·
class: Keyword to declare a class.
·
ClassName: By convention, class
names start with an uppercase letter (e.g., MyClass
, BankAccount
).
Creating Objects
Once a class is
defined, create objects using the new
keyword:
ClassName
objectName
=
new
ClassName(
);
·
ClassName: The class to
instantiate.
·
objectName: Reference variable
holding the object.
·
new: Allocates memory for the object.
·
ClassName(): Calls the constructor.
Accessing Class Members
objectName.fieldName
;
// Access a field
objectName.methodName
(
);
// Call a method
// Dog.java
public
class Dog {
// Fields
String name;
String breed;
// Methods
// Makes the dog bark
public void bark() {
System.out.println(name + " says: Woof! Woof!");
}
// Simulates the dog eating
public void eat() {
System.out.println(name + " is eating its food.");
}
// Displays the dog's information
public void displayInfo() {
System.out.println("Name: " + name + ", Breed: " + breed);
}
// Main method to run the program
public static void main(String[] args) {
// Create first Dog object
Dog myDog = new Dog();
myDog.name = "Buddy";
myDog.breed = "Golden Retriever";
// Create second Dog object
Dog anotherDog = new Dog();
anotherDog.name = "Lucy";
anotherDog.breed = "Labrador";
// Display information for myDog
System.out.println("--- Information for myDog ---");
myDog.displayInfo();
myDog.bark();
myDog.eat();
// Display information for anotherDog
System.out.println("\n--- Information for anotherDog ---");
anotherDog.displayInfo();
anotherDog.bark();
anotherDog.eat();
}
}
Explanation
·
The Dog
class has two fields: name
and breed
.
·
It defines three
methods: bark(
)
, eat()
, and displayInfo
()
.
·
Two objects (myDog
and anotherDog
) are created, each with its own state.
Example 2: Defining a
Car Class
// Car.java
public class Car {
// Fields
String make;
String model;
int year;
boolean isEngineOn;
// Methods
// Starts the car engine
public void start() {
if (!isEngineOn) {
isEngineOn = true;
System.out.println(make + " " + model + " engine started.");
} else {
System.out.println(make + " " + model + " engine is already running.");
}
}
// Stops the car engine
public void stop() {
if (isEngineOn) {
isEngineOn = false;
System.out.println(make + " " + model + " engine stopped.");
} else {
System.out.println(make + " " + model + " engine is already off.");
}
}
// Drives the car for a given distance if engine is on
public void drive(int distance) {
if (isEngineOn) {
System.out.println(make + " " + model + " is driving " + distance + " miles.");
} else {
System.out.println(make + " " + model + " cannot drive, engine is off.");
}
}
// Displays car information
public void displayCarInfo() {
System.out.println("Make: " + make + ", Model: " + model + ", Year: " + year + ", Engine On: " + isEngineOn);
}
// Main method to test the Car class
public static void main(String[] args) {
// Creating first Car object
Car myCar = new Car();
myCar.make = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;
// Creating second Car object
Car friendsCar = new Car();
friendsCar.make = "Honda";
friendsCar.model = "Civic";
friendsCar.year = 2020;
// Actions for myCar
System.out.println("--- My Car Actions ---");
myCar.displayCarInfo();
myCar.start();
myCar.drive(50);
myCar.stop();
// Actions for friend’s car
System.out.println("\n— Friend’s Car Actions —");
friendsCar.displayCarInfo();
friendsCar.drive(30); // Engine is off
friendsCar.start();
friendsCar.drive(30); // Engine is on
friendsCar.stop();
}
}