0% found this document useful (0 votes)
4 views34 pages

Copy of Session 8 - Classes and Objects - Part 1

This document provides an overview of classes and objects in Java, emphasizing their role in object-oriented programming. It explains the structure of class declarations, the significance of access modifiers, and the different members of a class, including fields, methods, constructors, and nested classes. Additionally, it highlights the benefits of using classes and objects, such as modularity, reusability, and maintainability.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views34 pages

Copy of Session 8 - Classes and Objects - Part 1

This document provides an overview of classes and objects in Java, emphasizing their role in object-oriented programming. It explains the structure of class declarations, the significance of access modifiers, and the different members of a class, including fields, methods, constructors, and nested classes. Additionally, it highlights the benefits of using classes and objects, such as modularity, reusability, and maintainability.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - II

Session 8 - Classes and Objects -


Part 1

1. Introduction to Classes and Objects

Introduction to Classes and Objects in Java


In Java, classes and objects are essential components of object-oriented programming (OOP).
They allow you to model real-world entities and their behaviors in a structured way.

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.

Example of a Class - Bank Account:

public class BankAccount {


// Fields (Attributes)
private String accountNumber; // Encapsulation - restrict direct access
private double balance;

// Method (Function) to deposit money


public void deposit(double amount) {
balance += amount;
}

// Method (Function) to withdraw money


public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient funds.");
}
}

// Constructor to initialize account details


public BankAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber; // Use 'this' to refer to current object
this.balance = initialBalance;
}
}

Explanation:

- 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.

Example of Creating a Bank Account Object:

public class Main {


public static void main(String[] args) {
// Create an object (instance) of the BankAccount class
BankAccount account1 = new BankAccount("ABC123", 100.00);

// Call object methods (public methods are accessible)


account1.deposit(50.00);
account1.withdraw(75.00);

// Display the current balance


System.out.println("Current Balance: $" + account1.balance); // Output: $75.00
}
}

Explanation:

- account1 is an object of the BankAccount class.


- new BankAccount("ABC123", 100.00) creates an instance of BankAccount with
the given account number and initial balance.
- We use deposit() and withdraw() methods to modify the object's state, and the
balance is accessed to display the current amount.

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

Class Declaration in Java


In Java, a class is a blueprint for creating objects. It encapsulates data and the operations that
can be performed on that data. The class declaration in Java is the starting point for defining the
structure and behavior of objects in an object-oriented program.

Basic Structure of a Class Declaration


A class declaration in Java includes several key components:

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:

[access_modifier] class ClassName [extends SuperClass] [implements Interface1,


Interface2, ...] {
// Fields (Attributes)
// Methods (Functions)
// Constructors
// Nested Classes
}

Components of Class Declaration


1. Access Modifiers:

- public: The class is accessible from any other class.


- protected: Not used directly on classes (used for members).
- default (no modifier): The class is accessible only within the same package.
- private: Not used with classes (used for members).

Example:

public class Animal {


// Class content
}

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:

- extends: Used to inherit from a superclass.


- implements: Used to implement one or more interfaces.

Example:

public class SavingsAccount extends BankAccount implements InterestBearing {


// Class content
}

5. Class Body:

- 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:

public class Car {


// Fields
private String model;
private String color;
private int year;

// 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.");
}

public void drive() {


System.out.println("Car is driving.");
}
}

Access Modifiers for Classes

Access Modifiers for Classes


In Java, access modifiers define the visibility or accessibility of a class to other classes and
packages. There are only two access modifiers available for top-level classes and four for
inner classes. The top-level class access modifiers are:

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.

Let's go into detail:

1. public Access Modifier


- Description: A class marked as public can be accessed from anywhere. This means
that any other class, regardless of package, can access the class.

- Visibility:

- Accessible from within its own package.


- Accessible from any class in any other package.

Example:

// File: Employee.java


public class Employee {
// Class definition
}

If a class is public, it can be accessed by any other class in the same or different
packages.

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.

2. default (Package-Private) Access Modifier


- Description: If no access modifier is specified, the class is given default access (also
called package-private access).

- Visibility:

- Accessible by other classes within the same package.


- Not accessible from classes in other packages.

Example:

// File: Employee.java


class Employee {
// Class definition
}

If a class is declared with no modifier, it is accessible only to classes in the same
package. Other classes in different packages cannot see or use this class.

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.

3. private Access Modifier (for Inner Classes Only)


- Description: The private access modifier can be used only for inner classes
(classes declared inside another class). A private inner class is accessible only within
the enclosing outer class.

- Visibility:

- Accessible only within the enclosing class.

Example:
public class OuterClass {
private class InnerClass {
// Private inner class, accessible only within OuterClass
}
}

Notes:

● It cannot be used for top-level classes.


● A private inner class is hidden from all other classes except the outer class.

4. protected Access Modifier (for Inner Classes Only)


- Description: Like private, the protected access modifier is only applicable to inner
classes. A protected inner class is accessible within the same package and by
subclasses in other packages.

- Visibility:

- Accessible by other classes in the same package.


- Accessible by subclasses in other packages.

Example:

public class OuterClass {


protected class InnerClass {
// Protected inner class, accessible in the same package and by subclasses
}
}

Key points:

● Cannot be used for top-level classes.


● Allows visibility to subclasses even in different packages.

Summary of Top-Level Class Access Modifiers:


Modifier Visibility Example

public Accessible from any class in any public class Employee


package.

default Accessible only within the same class Employee


package.
Summary of Inner Class Access Modifiers:
Modifier Visibility Example

public Accessible from any class in any public class Inner


package.

default Accessible only within the same class Inner


package.

private Accessible only within the private class Inner


enclosing class.

protected Accessible within the same protected class Inner


package and subclasses.

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:

1. Fields (Instance Variables)


Fields are variables that hold the data or state of an object. Each object created from a class
has its own copy of the instance variables.

Syntax:

class ClassName {

// Field declaration

dataType fieldName;


- Example:

class Car {

String model; // Field (instance variable)

String color; // Field (instance variable)


- 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;

// Method to display car details


void displayDetails() {
System.out.println("Model: " + model + ", Color: " + color);
}
}

- Explanation: The displayDetails() method prints the model and color of the Car
object. Methods often interact with the fields of the class.

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;

// Constructor to initialize fields

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.

- Static Fields: Shared among all instances of a class.

- Static Methods: Can be called without creating an object of the class.

- Example:
class Car {

String model;

String color;

static int numberOfCars; // Static field

// Constructor increments static field

Car(String model, String color) {

this.model = model;

this.color = color;

numberOfCars++; // Increments each time a car is created

static void displayNumberOfCars() { // Static method

System.out.println("Total Cars: " + numberOfCars);


- 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;

class InnerClass { // Non-static nested class (Inner class)


void display() {
System.out.println("Outer Field: " + outerField);
}
}

static class StaticNestedClass { // Static nested class


void staticMethod() {
System.out.println("Static Nested Class");
}
}
}

- Explanation: The InnerClass can access members of the outer class, while the
StaticNestedClass behaves like a regular class but is scoped inside the outer class.

6. Access Modifiers for Members


Members of a class can have different access levels, controlled by access modifiers:

- public: Accessible from any class.

- private: Accessible only within the same class.

- protected: Accessible within the same package or subclasses.

- (default) (no modifier): Accessible within the same package.

- Example:
class Car {

public String model; // Public field

private String color; // Private field

// Public method

public void displayDetails() {

System.out.println("Model: " + model);

// Private method

private void secretMethod() {

System.out.println("This is a private method.");

- Explanation: The model field and displayDetails() method are accessible


anywhere, while the color field and secretMethod() can only be accessed
within the Car class.
5. Objects

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.

Example of an Object: Car


Consider a real-life example of a car. Each car object will have properties like make, model, and
year (state), and behaviors like start, stop, and accelerate (methods).

Declaring and Initializing Objects

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:

// Declaring an object of type Car


Car myCar;

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:

// Class Declaration


public class Car {
// Instance Variables
String make;
String model;
int year;

// 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;
}

public static void main(String[] args) {


Car myCar = new Car("Toyota", "Corolla", 2022);
System.out.println(myCar.toString());
}
}

Output:

Car make: Toyota, model: Corolla, year: 2022

Ways to Create Objects


1. Using new Keyword

This is the most common method for object creation.

Car car1 = new Car("Honda", "Civic", 2023);



2. Using Class.forName(String className)

This method is used for creating an object by specifying the class name in a string
format.

Car car2 = (Car) Class.forName("Car").newInstance();



3. Using clone() Method
This method creates a copy of an existing object.

Car car3 = new Car("Ford", "Focus", 2021);


Car car4 = (Car) car3.clone();

4. Deserialization

Objects can also be created by reading from a serialized file.

FileInputStream file = new FileInputStream("car.ser");


ObjectInputStream in = new ObjectInputStream(file);
Car deserializedCar = (Car) in.readObject();

Creating Multiple Objects Using One Type


It's often practical to manage multiple objects using a single type reference. For example,
managing different types of vehicles using a common interface.

Example:

interface Vehicle {
void start();
}

class Bike implements Vehicle {


public void start() {
System.out.println("Bike started.");
}
}

class Truck implements Vehicle {


public void start() {
System.out.println("Truck started.");
}
}

public class Test {


public static void main(String[] args) {
Vehicle myVehicle;
myVehicle = new Bike();
myVehicle.start(); // Output: Bike started.
myVehicle = new Truck();
myVehicle.start(); // Output: Truck started.
}
}
Anonymous Objects in Java
Anonymous objects are instances that are created without assigning them to a reference
variable. They are typically used for immediate method calls and are discarded after use.

Example:

new Button().setOnAction(new EventHandler<ActionEvent>() {


@Override
public void handle(ActionEvent event) {
System.out.println("Button clicked!");
}
});

Difference Between Java Classes and Objects


- Class: A blueprint for creating objects. It defines the structure and behavior common to
all objects of that type.
- Example: Car class.
- Object: An instance of a class. Each object has its own state and can perform its own
behaviors.
- Example: myCar object of type Car.
6. Methods

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:

public class Calculator {

// Method to add two numbers


public int add(int num1, int num2) {
int sum = num1 + num2;
return sum; // Return the calculated sum
}

// Method to greet someone


public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}

Types of Methods in Java

Methods in Java can be broadly categorized into two types:

1. Predefined Methods (Standard Library Methods)

● 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:

○ Math.sqrt(x): Calculates the square root of a number.

○ System.out.println(message): Prints a message to the console.


○ Character.isDigit(char): Checks if a character is a digit.

○ Arrays.sort(array): Sorts an array of elements.

2. User-Defined Methods

● Definition: These methods are created by programmers to encapsulate specific logic or


functionality within their code.

● Customization: You can tailor them to meet your specific requirements.

● Structure: They follow the standard Java method syntax:

[access_modifier] return_type method_name(parameter_list) {


// Method body
}
● Example:

public class MyCalculator {


public int add(int a, int b) {
return a + b;
}
}

Ways to Create Methods in Java

Methods in Java can be classified into two main categories:

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.

2. Class Methods (Static Methods)

● Definition: Class methods are not associated with specific objects and can be called
directly using the class name.

● Calling: You can call class methods without creating an object.

● Access to data: Class methods cannot directly access or modify the fields of individual
objects.

Example:

public class MathUtils {


public static int add(int a, int b) {
return a + b;
}
}
// Calling the class method
int result = MathUtils.add(5, 3);
System.out.println(result); // Output: 8

Benefits of Using Methods:
● Code Reusability: Methods allow you to write code once and use it multiple times in
your program, saving time and effort.

● Improved Readability: By breaking complex logic into smaller, well-named methods,


your code becomes easier to understand and maintain.

● Modularization: Methods promote modularity by separating functionalities into


manageable units, making your code cleaner and more organized.
● Encapsulation: Methods help encapsulate data and logic within a class, promoting data
protection and access control.
Calling Methods:
Methods are the building blocks of Java programs, encapsulating specific tasks. How do you
actually use them? Here we will see method calling, the process of activating a method's
functionality.

When a Method Returns:

A method gives back control to the calling code when:

● All statements in the method body execute: If the method doesn't contain a

return statement, it implicitly returns after completing all its instructions.

● A return statement is reached: The return statement allows a method to send

a value back to the calling code. The returned value can be of any data type,

including primitives (e.g., int, double) or objects.

● An exception is thrown: Sometimes, a method might encounter an unexpected

error. It can throw an exception to signal the problem to the calling code, which

can then handle it accordingly.

Examples:

1. Simple Addition:

public class Calculator {


public int add(int a, int b) {
int sum = a + b;
return sum; // Return the calculated sum
}
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator(); // Create a Calculator object
int result = calc.add(5, 3); // Call the add() method with
arguments
System.out.println(result); // Output: 8
}
}

In this example, the add() method returns the calculated sum using the return

statement.

2. Printing a Greeting:

public class Greeter {


public void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}

public class Main {


public static void main(String[] args) {
Greeter greeter = new Greeter(); // Create a Greeter object
greeter.sayHello("Alice"); // Call the sayHello() method with an
argument
}
}

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

values) that match the method's parameter list.

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

Certainly! Here are some multiple-choice questions on the declaration


of methods and return values in Java:

1. What is the purpose of the return keyword in a method?

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

Answer: C) To exit a method and optionally return a value

2. Which of the following is the correct syntax for declaring a method that returns an
integer value?

A) int methodName() { // method body }


B) methodName() int { // method body }
C) methodName() { int // method body }
D) int { methodName() // method body }

Answer: A) int methodName() { // method body }

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

Answer: B) The method will not compile

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

5. How do you specify the return type of a method?

A) By placing it before the method name


B) By placing it after the method name
C) By using the return keyword
D) By using the void keyword

Answer: A) By placing it before the method name

7. Assigning One Object to Another

Assigning One Object to Another


When assigning one object to another in Java, what actually happens is that the reference (or
memory address) of the object is copied, rather than the object itself. This means that both
variables (the one being assigned and the one receiving the assignment) will refer to the same
object in memory. Here's an explanation with an example:

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;

Car(String model, String color) {


this.model = model;
this.color = color;
}

void display() {
System.out.println("Model: " + model + ", Color: " + color);
}
}

public class Main {


public static void main(String[] args) {
Car car1 = new Car("Tesla", "Red");
Car car2 = car1; // Assigning car1 to car2

car2.color = "Blue"; // Changing color via car2

// Both car1 and car2 will reflect the same data


car1.display(); // Output: Model: Tesla, Color: Blue
car2.display(); // Output: Model: Tesla, Color: Blue
}
}

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

1. How do you declare an object of a class in Java?


a) ClassName objectName;
b) ClassName objectName = new ClassName();
c) objectName = new ClassName();
d) new objectName = ClassName();

Answer: b) ClassName objectName = new ClassName();

2. What does the new keyword do in object creation?


a) It declares a class.
b) It initializes a class.
c) It creates an instance of a class.
d) It assigns a value to an attribute.

Answer: c) It creates an instance of a class.

3. In the statement Person p = new Person();, what is p?


a) A class
b) A method
c) An object
d) A constructor

Answer: c) An object

4. Which statement is true about object declaration in Java?


a) An object must be declared and initialized in separate statements.
b) Objects can only be declared if the class is defined.
c) The new keyword is optional when declaring an object.
d) Objects are automatically initialized without the new keyword.

Answer: b) Objects can only be declared if the class is defined.

5. What happens when you assign one object to another in Java?


a) A new object is created.
b) Both variables reference the same object.
c) Only the first object is updated.
d) The original object is destroyed.

Answer: b) Both variables reference the same object.

6. Which statement correctly assigns objectB to objectA?


a) objectA = objectB;
b) objectB = objectA;
c) objectA == objectB;
d) objectA.equals(objectB);

Answer: a) objectA = objectB;

7. What is the result of modifying an attribute of an object after assigning it to


another object?
a) Only the original object is modified.
b) Only the assigned object is modified.
c) Both objects reflect the changes.
d) No change occurs to either object.

Answer: c) Both objects reflect the changes.

8. When you assign an object to another, what is being copied?


a) The actual object
b) The reference to the object
c) The class definition
d) The object's data only

Answer: b) The reference to the object.

References
End of Session - 8

You might also like