Copy of Session 8 - Classes and Objects - Part 1
Copy of Session 8 - Classes and Objects - Part 1
THROUGH JAVA
UNIT - II
What is a Class?
A class serves as a blueprint for creating objects. It defines a set of attributes (fields) and
behaviors (methods) that the objects of the class will possess. You can think of a class as a
recipe that outlines the ingredients (attributes) and the steps (methods) for creating a specific
type of object.
Members of a Class:
1. Fields (Attributes): Variables that store data specific to an object. These represent the
state or characteristics of the object.
2. Methods (Functions): Functions that define the actions and behaviors an object can
perform. These represent what the object can do.
3. Constructors: Special methods used to initialize objects when they are created. They
set up the initial state of the object.
4. Nested Classes: Classes defined within another class to improve organization and
encapsulation.
- Fields: accountNumber and balance are attributes that represent the state of the
BankAccount object.
- Methods: deposit() and withdraw() define the behaviors related to managing the
account balance.
- Constructor: BankAccount(String accountNumber, double
initialBalance) initializes the object with the provided account number and initial
balance.
What is an Object?
An object is an instance of a class. It represents a specific realization of the class with its own
unique data and behaviors. For example, creating a BankAccount object from the
BankAccount class is like baking a cake from a recipe; each cake (object) may have its own
unique characteristics.
Creating an Object:
To create an object, you use the new keyword followed by a call to the class's constructor.
Key Points
- Encapsulation: Classes encapsulate data and methods, ensuring that internal details
are hidden and only accessible through well-defined interfaces.
- Abstraction: Classes abstract complex real-world entities into simplified
representations, making it easier to manage and interact with them.
- Instance Creation: Each object created from a class has its own distinct set of attributes
and methods, allowing for unique interactions.
Benefits of Using Classes and Objects
- Modularity: Code is organized into manageable and reusable units, making it easier to
develop and maintain.
- Reusability: Classes can be reused to create multiple objects, reducing redundancy and
improving efficiency.
- Maintainability: Changes to the class implementation are isolated from other code,
making it easier to manage and update the system.
By understanding and applying these concepts, you can build more structured and efficient Java
programs that effectively model real-world scenarios.
2. Class Declaration
1. Access Modifiers (optional): These define the visibility of the class to other classes.
2. Class Keyword: This is used to declare a class.
3. Class Name: A unique identifier for the class.
4. Superclasses and Interfaces (optional): Defines the inheritance and interface
implementation.
5. Class Body: Enclosed in curly braces {}, this contains fields, methods, constructors,
and nested classes.
Syntax:
Example:
2. class Keyword: It is used to declare a class, which serves as a blueprint for creating
objects.
3. Class Name:
- The class name must be a valid Java identifier and follow naming conventions
(e.g., Employee, BankAccount).
- By convention, class names start with an uppercase letter.
Example:
class BankAccount {
// Class content
}
4. Superclasses and Interfaces:
Example:
- The class body contains the class's fields (attributes), methods (functions),
constructors, and any nested classes.
- Everything inside the class body defines the structure and behavior of the objects
created from the class.
Example:
// Constructor
public Car(String model, String color, int year) {
this.model = model;
this.color = color;
this.year = year;
}
// Methods
public void startEngine() {
System.out.println("Engine started.");
}
1. public
2. default (no modifier)
For inner classes, Java allows the use of private and protected access modifiers in
addition to public and default.
- Visibility:
Example:
Key points:
● The class must be in a file that has the same name as the class (e.g.,
Employee.java).
● Only one public class is allowed per source file.
- Visibility:
Example:
Key points:
● This is useful when you want to encapsulate functionality within the same
package.
● No special keyword is used for default access; simply omit the modifier.
- Visibility:
Example:
public class OuterClass {
private class InnerClass {
// Private inner class, accessible only within OuterClass
}
}
Notes:
- Visibility:
Example:
Key Takeaways:
- Top-level classes can only use public or default (package-private) access.
- Inner classes can use all four access modifiers (public, protected, default, and
private).
- Default access means the class or method is visible only to other classes in the same
package.
- Public classes can be accessed from anywhere, but the file name must match the class
name.
By controlling the access level of your classes, you can encapsulate your code and maintain its
integrity, ensuring that only the appropriate parts of your program are exposed to external
packages.
4. Members
Class members
It refer to the fields (also called instance variables), methods, constructors, and nested classes
defined within a class. These members define the behavior and state of the objects created
from the class. Here's a detailed breakdown of each type of member:
Syntax:
class ClassName {
// Field declaration
dataType fieldName;
- Example:
class Car {
- Explanation: In this example, each Car object will have its own model and color.
2. Methods
Methods define the behavior of objects. They contain the logic that manipulates the fields of the
object or performs specific actions.
- Syntax:
class ClassName {
// Method declaration
returnType methodName(parameters) {
// Method body
- Example:
class Car {
String model;
String color;
3. Constructors
A constructor is a special method used to initialize objects. It is called when an object is created
using the new keyword. Constructors usually set initial values for fields.
- Syntax:
class ClassName {
// Constructor declaration
ClassName(parameters) {
// Constructor body
- Example:
class Car {
String model;
String color;
this.model = model;
this.color = color;
}
- Explanation: The constructor Car(String model, String color) is called when
an object of Car is created, and it initializes the model and color fields.
4. Static Members
Static members belong to the class rather than any specific object. Static fields and methods
are shared by all objects of the class.
- Example:
class Car {
String model;
String color;
this.model = model;
this.color = color;
- Explanation: The numberOfCars field is shared across all instances of the Car class,
and the static method displayNumberOfCars() can be called without creating a Car
object.
5. Nested Classes
A class can contain another class inside it. These are called nested classes. Nested classes
can be static or non-static.
- Example:
class OuterClass {
int outerField;
- Example:
class Car {
// Public method
// Private method
Java Objects
In Java, objects are fundamental units of Object-Oriented Programming (OOP) and represent
real-life entities. Objects are instances of classes, embodying both state and behavior, and
interact with each other through methods.
Components of an Object
1. State: Represented by the attributes or properties of the object.
2. Behavior: Represented by the methods or functions of the object.
3. Identity: A unique identifier that distinguishes one object from another.
Declaring Objects
To declare an object in Java, you define a reference variable of the class type. This declaration
does not allocate memory for the object. Memory is allocated when you actually create
(instantiate) the object using the new keyword.
Example:
Initializing Objects
To create an object, you use the new keyword followed by a constructor. This allocates memory
for the object and invokes the class constructor.
Example:
// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Methods
public String getMake() { return make; }
public String getModel() { return model; }
public int getYear() { return year; }
@Override
public String toString() {
return "Car make: " + make + ", model: " + model + ", year: " + year;
}
This method is used for creating an object by specifying the class name in a string
format.
Example:
interface Vehicle {
void start();
}
Example:
Methods
Methods, also known as functions, are the heart and soul of object-oriented programming in
Java. They are reusable blocks of code that perform specific tasks within a class. Imagine them
as mini-machines that take inputs (parameters), process them, and often deliver an output
(return value) or perform an action.
Parts of a Method:
A method declaration typically consists of six components:
1. Access Modifier (Optional): Controls where the method can be called from. Common
options include public (accessible anywhere), private (accessible only within the
class), and protected (accessible within the class and subclasses).
2. Return Type (Mandatory): Specifies the data type of the value the method returns (e.g.,
int, double, String, or void if it doesn't return anything).
3. Method Name (Mandatory): A descriptive name that reflects its functionality (use
lowercase with camelCase for multiple words).
4. Parameter List (Optional): A comma-separated list of variables (parameters) that the
method accepts as input, along with their data types. Empty parentheses () indicate no
parameters.
5. Method Body (Optional): The code block enclosed in curly braces {} that contains the
instructions the method executes.
6. Throws Clause (Optional): Declares exceptions the method might throw, allowing for
error handling.
Example:
● Definition: These methods are built-in functions that are part of the Java class libraries.
They provide essential functionalities for various tasks.
● Accessibility: You can use them directly in your code without defining them yourself.
● Examples:
2. User-Defined Methods
1. Instance Methods
● Definition: These methods are associated with specific objects and can access and
modify the object's data (fields).
● Calling: You need to create an object of the class and use the dot notation to call
instance methods.
● Access to data: Instance methods can directly access and modify the fields of the
object they are called on.
Example:
public class Person {
private String name;
private int age;
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
// Creating an object and calling the instance method
Person person = new Person("Alice", 30);
person.introduce(); // Output: Hello, my name is Alice and I am 30 years old.
● Definition: Class methods are not associated with specific objects and can be called
directly using the class name.
● Access to data: Class methods cannot directly access or modify the fields of individual
objects.
Example:
● All statements in the method body execute: If the method doesn't contain a
a value back to the calling code. The returned value can be of any data type,
error. It can throw an exception to signal the problem to the calling code, which
Examples:
1. Simple Addition:
In this example, the add() method returns the calculated sum using the return
statement.
2. Printing a Greeting:
Here, the sayHello() method doesn't explicitly return a value, but it prints a message
to the console.
Remember: When calling a method, you provide the necessary arguments (input
Do It Yourself
1. Write a method that takes two integers as parameters and returns their sum. Then, call
this method from the main method and print the result.
2. Create a method that takes a string as a parameter and returns the string in uppercase.
Call this method from the main method and display the result.
3. Define an overloaded method named multiply that can handle both integer and
double parameters. Write code to call these methods and print the results.
Quiz
A) To declare a method
B) To define the method's return type
C) To exit a method and optionally return a value
D) To call another method
2. Which of the following is the correct syntax for declaring a method that returns an
integer value?
3. What will happen if a method with a non-void return type does not include a return
statement?
A) The code will compile and run with a default return value
B) The method will not compile
C) The method will return null by default
D) The code will throw a runtime exception
4. Which keyword is used to define a method that does not return any value?
A) public
B) return
C) static
D) void
Answer: D) void
Concept:
In Java, objects are reference types, which means that when you assign one object to another,
you're copying the reference (not the actual object). If you modify the object using either
reference, both will reflect the changes because they point to the same memory location.
Syntax:
ClassName obj1 = new ClassName();
ClassName obj2 = obj1;
- obj1 and obj2 are now references to the same object in memory.
Example:
class Car {
String model;
String color;
void display() {
System.out.println("Model: " + model + ", Color: " + color);
}
}
Explanation:
- In the example above, car1 and car2 point to the same Car object in memory.
- When the color is changed using car2, the change is reflected in car1 as well
because they both reference the same object.
Important Notes:
- This only applies to object references (not primitive types like int, float, etc.).
- If you need to create a new object with the same data, you'd have to explicitly copy the
object or use a constructor that clones the values from one object to another.
Do It Yourself
1. Write a Java program to define a class Book with attributes title, author, and price.
Create an object of this class, assign values to the attributes, and print them.
2. Write a Java program to create a class Rectangle with attributes length and width, and
a method calculateArea(). Create an object, set the values of the attributes, and print the
area of the rectangle.
Quiz
Answer: c) An object
References
End of Session - 8