[go: up one dir, main page]

0% found this document useful (0 votes)
10 views14 pages

Chapter 3

The document provides an overview of object-oriented programming (OOP) concepts in Java, focusing on classes and objects. It explains how to define classes, create objects, and the key principles of OOP such as encapsulation, inheritance, and polymorphism. Additionally, it discusses the characteristics and usage of object variables, constructors, and methods in Java.

Uploaded by

ambachewm27
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)
10 views14 pages

Chapter 3

The document provides an overview of object-oriented programming (OOP) concepts in Java, focusing on classes and objects. It explains how to define classes, create objects, and the key principles of OOP such as encapsulation, inheritance, and polymorphism. Additionally, it discusses the characteristics and usage of object variables, constructors, and methods in Java.

Uploaded by

ambachewm27
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/ 14

In Java, objects and classes are fundamental concepts in object-oriented programming (OOP).

They provide a way to model real-world entities and their interactions in a structured manner.
Here’s an in-depth look at both concepts.

1. Classes

A class is a blueprint or template for creating objects. It defines the properties (attributes) and
behaviors (methods) that the objects created from the class will have.

a. Defining a Class

Syntax:

java
Copy code
class ClassName {
// Attributes (fields)
dataType attribute1;
dataType attribute2;

// Constructor
ClassName(parameters) {
// Initialization code
}

// Methods
returnType methodName(parameters) {
// Method body
}
}

Example:

java
Copy code
class Car {
// Attributes
String color;
String model;
int year;

// Constructor
Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}

// Method
void displayInfo() {
System.out.println("Car Model: " + model + ", Color: " + color + ",
Year: " + year);
}
}

2. Objects

An object is an instance of a class. When you create an object, you allocate memory for it and
initialize its attributes.

a. Creating an Object

You create an object using the new keyword, which calls the constructor of the class.

Syntax:

java
Copy code
ClassName objectName = new ClassName(arguments);

Example:

java
Copy code
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Red", "Toyota Camry", 2020);

// Calling a method on the object


myCar.displayInfo(); // Output: Car Model: Toyota Camry, Color: Red,
Year: 2020
}
}

3. Key Concepts

a. Attributes and Methods

 Attributes (Fields): Variables that hold the state of an object. They define the
characteristics of the object.
 Methods: Functions defined in a class that describe the behaviors of the object. They can
perform actions, manipulate data, and interact with other objects.

b. Constructor

A constructor is a special method that is called when an object is created. It is used to initialize
the attributes of the object. A class can have multiple constructors (constructor overloading) with
different parameters.

c. Encapsulation
Encapsulation is a principle in OOP that restricts direct access to an object’s attributes. Instead,
you use methods (getters and setters) to access and modify the attributes.

Example of Encapsulation:

java
Copy code
class Person {
private String name; // Private attribute

// Constructor
Person(String name) {
this.name = name;
}

// Getter method
public String getName() {
return name;
}

// Setter method
public void setName(String name) {
this.name = name;
}
}

d. Inheritance

Inheritance is a mechanism that allows one class (subclass) to inherit the attributes and methods
of another class (superclass). This promotes code reuse and establishes a hierarchical
relationship.

Example of Inheritance:

java
Copy code
class Vehicle {
String brand;

void honk() {
System.out.println("Beep beep!");
}
}

class Bike extends Vehicle {


int wheels;

Bike(String brand, int wheels) {


this.brand = brand;
this.wheels = wheels;
}

void displayInfo() {
System.out.println("Bike Brand: " + brand + ", Wheels: " + wheels);
}
}

4. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common


superclass. It enables method overriding and dynamic method dispatch.

Example of Polymorphism:

java
Copy code
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Meow");
}
}

public class TestPolymorphism {


public static void main(String[] args) {
Animal myDog = new Dog(); // Upcasting
Animal myCat = new Cat(); // Upcasting

myDog.sound(); // Output: Bark


myCat.sound(); // Output: Meow
}
}

Summary

 Classes: Blueprints for creating objects, defining attributes and methods.


 Objects: Instances of classes, representing specific entities with state and behavior.
 Key Concepts: Encapsulation, inheritance, and polymorphism are fundamental OOP
principles that enhance code organization and reusability.

In Java, object variables (often referred to as instance variables) are attributes associated with an
object. They are used to store the state or properties of an object created from a class.
Understanding object variables is essential for effective object-oriented programming (OOP) in
Java. Here’s a detailed explanation of object variables, their characteristics, and usage.
1. What are Object Variables?

Object variables are defined within a class and represent the data or state of an object. Each
object created from a class has its own copy of the object's variables. This allows each object to
maintain its own state independently of other objects.

2. Defining Object Variables

Object variables are typically defined within a class, outside of any method, and can be assigned
access modifiers (such as private, protected, or public) to control their visibility.

a. Example of Defining Object Variables

java
Copy code
class Dog {
// Object variables (instance variables)
String name; // Public by default
int age; // Public by default
String breed; // Public by default

// Constructor to initialize object variables


Dog(String name, int age, String breed) {
this.name = name;
this.age = age;
this.breed = breed;
}

// Method to display dog details


void displayInfo() {
System.out.println("Dog Name: " + name + ", Age: " + age + ", Breed: "
+ breed);
}
}

3. Accessing Object Variables

You can access object variables using the object reference and the dot (.) operator.

a. Example of Accessing Object Variables

java
Copy code
public class Main {
public static void main(String[] args) {
// Creating an object of the Dog class
Dog myDog = new Dog("Buddy", 3, "Golden Retriever");

// Accessing and modifying object variables


System.out.println("Name: " + myDog.name); // Output: Name: Buddy
myDog.age = 4; // Modifying the age
System.out.println("Updated Age: " + myDog.age); // Output: Updated
Age: 4

// Calling a method to display information


myDog.displayInfo(); // Output: Dog Name: Buddy, Age: 4, Breed: Golden
Retriever
}
}

4. Characteristics of Object Variables

1. Instance-Specific: Each object has its own copy of the instance variables. Changing the
value of an instance variable in one object does not affect the same variable in other
objects.

Example:

java
Copy code
Dog dog1 = new Dog("Buddy", 3, "Labrador");
Dog dog2 = new Dog("Max", 2, "Beagle");
dog1.age = 4; // Changes age of dog1 only
System.out.println(dog2.age); // Output: 2

2. Default Values: Object variables have default values if not explicitly initialized. For
example, numeric types default to 0, booleans default to false, and object references
default to null.

Example:

java
Copy code
class Cat {
String name; // Defaults to null
int age; // Defaults to 0
}
Cat myCat = new Cat();
System.out.println("Name: " + myCat.name); // Output: Name: null
System.out.println("Age: " + myCat.age); // Output: Age: 0

3. Access Modifiers: The visibility of object variables can be controlled using access
modifiers:
o private: Accessible only within the same class.
o protected: Accessible within the same package and subclasses.
o public: Accessible from any other class.

Example:

java
Copy code
class Car {
private String model; // Private variable
public int year; // Public variable

// Constructor
Car(String model, int year) {
this.model = model;
this.year = year;
}

// Getter method for private variable


public String getModel() {
return model;
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car("Tesla", 2023);
System.out.println("Car Year: " + myCar.year); // Accessible
// System.out.println("Car Model: " + myCar.model); // Error:
model has private access
System.out.println("Car Model: " + myCar.getModel()); //
Accessible via getter
}
}

5. Conclusion

Object variables are a crucial aspect of OOP in Java, allowing you to store the state of objects
and encapsulate their behavior. Understanding how to define, access, and manipulate object
variables will enable you to create robust and modular Java applications.

If you have any questions or need further clarification on object variables or related topics, feel
free to ask!

Defining a class in object-oriented programming (OOP) in Java is a fundamental concept that


allows you to create blueprints for objects. A class encapsulates data for the object and methods
to manipulate that data. Here’s a detailed explanation of how to define a class in Java, including
syntax, components, and examples.

1. What is a Class?

A class is a blueprint or template from which objects are created. It defines the properties
(attributes) and behaviors (methods) that the objects of that class will have.

2. Syntax for Defining a Class

The basic syntax for defining a class in Java is as follows:

java
Copy code
[access_modifier] class ClassName {
// Attributes (instance variables)
dataType variableName;

// Constructor
ClassName(parameters) {
// Initialization code
}

// Methods
returnType methodName(parameters) {
// Method body
}
}

Components of a Class Definition

1. Access Modifier: Specifies the visibility of the class. Common modifiers include:
o public: Accessible from any other class.
o private: Accessible only within the same class (not applicable to top-level classes).
o protected: Accessible within the same package and subclasses.

2. Class Name: Should start with an uppercase letter by convention and follow CamelCase.
3. Attributes: Variables that hold the state of the object. They are defined at the class level.
4. Constructor: A special method that is called when an object of the class is created. It
usually initializes the attributes.
5. Methods: Functions defined in the class that define the behaviors of the object.

3. Example of Defining a Class

Let’s create a class named Car that has attributes like model, year, and color, along with a
constructor and methods to display information about the car.

Example Code
java
Copy code
// Class definition
public class Car {
// Attributes (instance variables)
private String model; // Private attribute
private int year; // Private attribute
private String color; // Private attribute

// Constructor to initialize object variables


public Car(String model, int year, String color) {
this.model = model; // Initialize model
this.year = year; // Initialize year
this.color = color; // Initialize color
}
// Method to display car details
public void displayInfo() {
System.out.println("Car Model: " + model + ", Year: " + year + ",
Color: " + color);
}

// Getter for model


public String getModel() {
return model;
}

// Setter for model


public void setModel(String model) {
this.model = model;
}
}

Key Points in the Example

 Attributes: The class has three private attributes: model, year, and color. These are
marked as private to encapsulate the data, meaning they cannot be accessed directly
outside the class.
 Constructor: The Car constructor initializes the object attributes when a new Car object
is created.
 Methods: The displayInfo method is a public method that displays the car's details.
The class also includes getter and setter methods for the model attribute to allow
controlled access and modification.

4. Creating Objects from the Class

You can create objects from the Car class using the new keyword:

Example of Creating an Object


java
Copy code
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car("Toyota Camry", 2022, "Blue");

// Calling the method to display car information


myCar.displayInfo(); // Output: Car Model: Toyota Camry, Year: 2022,
Color: Blue

// Using getter and setter methods


System.out.println("Current Model: " + myCar.getModel()); // Output:
Current Model: Toyota Camry
myCar.setModel("Honda Accord");
System.out.println("Updated Model: " + myCar.getModel()); // Output:
Updated Model: Honda Accord
}
}

Explanation of Object Creation

 The line Car myCar = new Car("Toyota Camry", 2022, "Blue"); creates a new Car
object and initializes its attributes using the constructor.
 The method myCar.displayInfo(); calls the method to print the car's details.
 The getter and setter methods allow access and modification of the model attribute.

5. Conclusion

Defining a class in Java is a foundational concept in object-oriented programming. It involves


specifying attributes and methods that define the behavior and state of objects. Understanding
how to create and use classes effectively allows developers to create modular, reusable, and
maintainable code.

If you have any questions or would like further clarification on any aspect of defining a class in
Java, feel free to ask!

3.3 Instantiating and Using Objects

In Java, instantiation refers to the creation of a specific object from a class. Once an object is
instantiated, it can be used to access the properties and methods defined in the class. Here’s a
detailed explanation of the instantiation process and how to use objects effectively.

1. Instantiation

To instantiate an object in Java, you use the new keyword followed by the class constructor.

Example:

java
Copy code
public class Dog {
String name;

// Constructor
public Dog(String name) {
this.name = name;
}

// Method to display the dog's name


public void bark() {
System.out.println(name + " says Woof!");
}
}

public class Main {


public static void main(String[] args) {
// Instantiating the Dog class
Dog myDog = new Dog("Buddy");

// Using the object


myDog.bark(); // Output: Buddy says Woof!
}
}

Key Points:

 Instantiation: The line Dog myDog = new Dog("Buddy"); creates a new Dog object
with the name "Buddy."
 Using Objects: The method myDog.bark(); calls the bark method on the myDog object.

3.4 Instance Fields, Constructors, and Methods

Instance Fields, Constructors, and Methods are essential components of a class in Java, each
serving a specific purpose:

1. Instance Fields

 Also known as instance variables or object variables, they store the state of an object.
 Each object has its own copy of instance fields.

Example:

java
Copy code
public class Car {
// Instance fields
private String model;
private int year;

// Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}

// Method to display car details


public void displayInfo() {
System.out.println("Car Model: " + model + ", Year: " + year);
}
}

2. Constructors

 A constructor is a special method that is called when an object is instantiated.


 It initializes the instance fields of the class.

Example:

java
Copy code
Car myCar = new Car("Toyota Camry", 2022); // Constructor initializes model
and year

3. Methods

 Methods define the behaviors of the class and can manipulate instance fields or perform
actions.
 They can be public, private, or protected based on how they should be accessed.

Example:

java
Copy code
public void displayInfo() {
System.out.println("Car Model: " + model + ", Year: " + year);
}

Example of Using Instance Fields, Constructors, and Methods


java
Copy code
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota Camry", 2022);
myCar.displayInfo(); // Output: Car Model: Toyota Camry, Year: 2022
}
}

3.5 Private and Public Data

In Java, access modifiers control the visibility and accessibility of class members (instance fields
and methods). The two most common modifiers are private and public.

1. Private Data

 Private members are accessible only within the same class.


 They are often used to implement encapsulation, allowing control over how the data can
be accessed or modified.

Example:

java
Copy code
public class BankAccount {
private double balance; // Private field

// Constructor
public BankAccount(double initialBalance) {
balance = initialBalance;
}

// Method to get the balance


public double getBalance() {
return balance; // Accessible within the class
}

// Method to deposit money


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

2. Public Data

 Public members are accessible from any other class.


 They are used when you want to expose certain functionalities or data of the class to
other parts of the program.

Example:

java
Copy code
public class Main {
public static void main(String[] args) {
BankAccount myAccount = new BankAccount(1000.0);
System.out.println("Balance: " + myAccount.getBalance()); //
Accessible
myAccount.deposit(500.0);
System.out.println("Updated Balance: " + myAccount.getBalance()); //
Accessible
}
}

Key Differences:

 Private: Restricts access to the class itself, protecting the data and ensuring it can only be
modified through methods (getters/setters).
 Public: Allows any other class to access and manipulate the data or call the methods,
promoting interaction with the object's state.
Conclusion

 Instantiating Objects: You create specific instances of a class using the new keyword.
 Instance Fields, Constructors, and Methods: Each class can have fields to store data,
constructors to initialize them, and methods to define behavior.
 Access Modifiers: private and public control the accessibility of data and methods,
ensuring encapsulation and controlled interaction between classes.

You might also like