Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
17 views

Class, Object, Variables Constructor

,m

Uploaded by

Musiclover Huu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Class, Object, Variables Constructor

,m

Uploaded by

Musiclover Huu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

In Java (and other object-oriented programming languages), a class is a blueprint or template for creating

objects. It defines a set of properties (also known as fields or attributes) and methods (functions or behaviors)
that the objects created from the class will have.

In Java and other object-oriented programming languages, an object is an instance of a class. It represents a specific
entity that contains both data (in the form of fields or attributes) and behavior (in the form of methods).

Difference Between Class and Object

Aspect Class Object


An object is an instance of a class. It
A class is a blueprint or template that defines
represents a specific entity with its own unique
Definition the structure and behavior (data and methods)
state and can perform actions defined by the
that objects created from the class will have.
class.
An object is created at runtime using the new
A class is defined in the code using the class
Creation keyword and a constructor, which allocates
keyword and is created at compile time.
memory for the object.
A class contains fields (attributes) and methods An object has its own copy of the class's fields
Structure (functions) that define the properties and and can execute the methods defined by the
behaviors of the objects. class.
Memory is allocated for an object when it is
Memory A class itself does not consume memory for
instantiated. This memory holds the object's
Allocation fields until an object is created.
instance variables.
class Car { String make; String model; Car myCar = new Car("Toyota",
Example int year; void displayInfo() { /* ... "Camry", 2021); — myCar is an object of the
*/ } } Car class.
A class is abstract and does not have a real An object is a concrete instance of a class,
Relationship
existence in memory; it's just a blueprint. existing in memory with a specific state.
An object is a specific instance; many objects
Number One class can be used to create many objects. can be created from the same class, each with
its own state.
Methods and fields in a class can be accessed
Instance methods and fields in an object are
Access using the class name (for static members) or
accessed using the object's reference variable.
through an object of the class.

Class Definition:

public class Car {


String make;
String model;
int year;

void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}

Creating Objects from the Class:

public class Main {


public static void main(String[] args) {
// Creating two objects of the Car class
Car car1 = new Car();
car1.make = "Toyota";
car1.model = "Camry";
car1.year = 2021;

Car car2 = new Car();


car2.make = "Honda";
car2.model = "Civic";
car2.year = 2020;

// Accessing object’s method


car1.displayInfo(); // Output: Make: Toyota, Model: Camry, Year: 2021
car2.displayInfo(); // Output: Make: Honda, Model: Civic, Year: 2020
}
}

Summary

 Class: The Car class defines what attributes and behaviors a car object will have.
 Object: car1 and car2 are specific instances of the Car class, each with its own make, model, and year.
These objects use the class's blueprint but hold their own unique data.

Instance Variables

1. Definition of Instance Variables

Instance variables are variables defined within a class for which each instantiated object of the class has its
own separate copy. These variables represent the attributes or properties of an object and are used to store the
object's state. Instance variables are declared within a class but outside any method, constructor, or block.

2. How to Access Instance Variables

Instance variables are accessed through objects. You can access and modify an instance variable using the
object reference followed by the dot operator (.) and the variable name.

3. Diagram for Reference and Object

Imagine a Car class with instance variables make, model, and year. When you create an object of this class, the
instance variables are stored in memory, and you access them via the object's reference.

Class: Car
-------------------------------------
| make | model | year |
-------------------------------------
Objects:

myCar1: myCar2:
--------------------- -------------------
| make = "Toyota" | | make = "Honda" |
| model = "Camry" | | model = "Civic" |
| year = 2021 | | year = 2020 |
-------------------- -------------------

Accessing Instance Variables:


myCar1.make -> "Toyota" myCar2.make -> "Honda"
myCar1.model -> "Camry" myCar2.model -> "Civic"
myCar1.year -> 2021 myCar2.year -> 2020

4. Example Code Without Access Modifiers


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

// Method to display car information


void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}

public static void main(String[] args) {


// Creating two objects of Car class
Car myCar1 = new Car("Toyota", "Camry", 2021);
Car myCar2 = new Car("Honda", "Civic", 2020);

// Accessing instance variables using object references


System.out.println("Car 1 Make: " + myCar1.make); // Output: Toyota
System.out.println("Car 2 Make: " + myCar2.make); // Output: Honda

// Displaying car information


myCar1.displayInfo();
myCar2.displayInfo();
}
}

5. Code Explanation

 Instance Variables: The Car class has three instance variables: make, model, and year. Each object
created from the Car class will have its own unique values for these variables.
 Constructor: The constructor Car(String make, String model, int year) initializes the instance
variables for each object. When an object is created, the values passed to the constructor are assigned to
the instance variables.
 Method displayInfo: This method prints out the values of the instance variables. Since instance
variables are tied to the specific object that calls the method, it will print the details of the object that
invokes it.
 Creating Objects: The main method creates two objects of the Car class (myCar1 and myCar2) with
different values for make, model, and year.
 Accessing Instance Variables: The instance variables are accessed directly using the object references
myCar1 and myCar2. For example, myCar1.make returns "Toyota", and myCar2.make returns "Honda".
 Output:
o When the program is run, it first prints the make of both cars directly.
o Then it calls the displayInfo() method on both myCar1 and myCar2, displaying the details of
each car.
Static Variables

1. Definition of Static Variables

In Java, static variables (also known as class variables) are variables that belong to the class rather than to
instances (objects) of the class. A static variable is shared among all instances of the class, meaning that if one
object modifies the static variable, the change is reflected across all objects of that class.

2. How to Access Static Variables

 Within the Class: You can access a static variable directly by its name.
 Outside the Class: You can access a static variable using the class name, like
ClassName.variableName.

3. Diagram for Reference and Object

Here’s a simple conceptual diagram to illustrate the difference between instance variables (object-specific) and
static variables (shared across all instances):

+------------------+
| Class |
+------------------+
| static int count |
+------------------+
|
| Shared among all instances
+-------+-------+-------+
| | | |
+-----v-----+ +-----v-----+ +-----v-----+
| Object1 | | Object2 | | Object3 |
+-----------+ +-----------+ +-----------+
| int value | | int value | | int value |
+-----------+ +-----------+ +-----------+

In the diagram:

 count is a static variable shared by all objects.


 Each object (Object1, Object2, Object3) has its own value variable.

4. Example Code Without Access Modifiers

public class Counter {


static int count = 0; // Static variable

Counter() {
count++; // Increment the static variable for each new object
}

void displayCount() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

c1.displayCount(); // Accessing the static variable via an object


System.out.println(Counter.count); // Accessing the static variable via the
class name
}
}

5. Code Explanation

 Static Variable Declaration: The count variable is declared as static in the Counter class, making it a
class-level variable shared by all instances of the class.
 Constructor: Each time a Counter object is created, the count variable is incremented. This means that
no matter how many objects are created, count will keep track of the total number.
 Accessing Static Variables:
o c1.displayCount(); demonstrates how you can access the static variable using an object.
o Counter.count; shows how you can access the static variable directly using the class name.

In this example, the count variable will be incremented three times because three Counter objects (c1, c2, and
c3) are created. The output will be:

Count: 3
3

This output shows that count holds the same value across all objects, confirming that it is indeed a shared
(static) variable.

Comparison between instance variables and static variables:

Aspect Instance Variables Static Variables


Definition Variables tied to a specific instance/object. Variables tied to the class itself.
Scope Accessible via the object reference. Accessible via the class name.
Memory Allocated per object; deallocated when the Allocated once per class; deallocated when the
Allocation object is destroyed. class is unloaded.
Default to standard values per object (e.g., Default to standard values shared among all
Default Values
0 for integers, null for objects). instances.
Accessed using an object reference (e.g., Accessed using the class name (e.g.,
Access
object.variable). ClassName.variable) or an object reference.
Used to store data shared among all instances or
Usage Used to store data specific to each object.
common to the class.
Aspect Instance Variables Static Variables
Initialized once for the class; shared across all
Initialization Initialized separately for each object.
objects.
Behavior Different objects can have different values. All objects share the same value.

This table summarizes the key differences between instance and static variables in Java.

A constructor
1. Definition with Example

A constructor is a special method in a class that is invoked when an object of the class is created. It has the
same name as the class and no return type. Its primary purpose is to initialize the new object.

Example:
public class Car {
String model;
int year;

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

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

public static void main(String[] args) {


Car myCar = new Car("Toyota", 2021); // Create an object using the constructor
myCar.displayInfo();
}
}

2. Application

Constructors are used to:

 Initialize the state of an object at the time of its creation.


 Set default values or specific initial values for object attributes.
 Ensure that objects are set up correctly before they are used.

3. Default Constructor

A default constructor is a no-argument constructor automatically provided by Java if no other constructors are
defined. It initializes instance variables to their default values.

Theoretical Points:

 Automatic Provision: If no constructor is explicitly defined, Java provides a default constructor.


 Initialization: It sets fields to their default values (e.g., 0 for numeric types, null for objects).
 Explicit Definition: If any other constructors are defined, the default constructor is not provided automatically.

4. How to Create a Default Constructor

If other constructors are defined, you need to explicitly define a default constructor if you want it.

Example:
public class Car {
String model;
int year;

// Default constructor
public Car() {
// Default initialization
model = "Unknown";
year = 0;
}

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

5. Types of Constructors with Examples

No-Argument Constructor

A constructor with no parameters.

public class Car {


String model;

// No-argument constructor
public Car() {
model = "Unknown";
}
}
Parameterized Constructor

A constructor that takes parameters to initialize fields with specific values.

public class Car {


String model;
int year;

// Parameterized constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
6. Use of this Keyword with Proper Examples

Example 1: Distinguishing Between Instance Variables and Parameters


public class Car {
String model;

// Parameterized constructor
public Car(String model) {
this.model = model; // 'this.model' refers to the instance variable
}
}
Example 2: Calling Another Constructor (Constructor Chaining)
public class Car {
String model;
int year;

// No-argument constructor
public Car() {
this("Unknown", 0); // Calls parameterized constructor
}

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

7. Constructor Chaining with Examples

Constructor chaining is when one constructor calls another constructor in the same class.

Example:
public class Car {
String model;
int year;

// No-argument constructor
public Car() {
this("Unknown", 0); // Calls the two-argument constructor
}

// Single-argument constructor
public Car(String model) {
this(model, 0); // Calls the two-argument constructor with a default year
}

// Two-argument constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
8. Copy Constructor (Application and Example Code)

A copy constructor creates a new object as a copy of an existing object. It is useful for copying objects with
complex states.

Application:

 Copying Objects: Useful when you need to create a duplicate of an object with the same state.
 Clone Operations: Can be used in custom cloning implementations.

Example Code:
public class Car {
String model;
int year;

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

// Copy constructor
public Car(Car other) {
this.model = other.model;
this.year = other.year;
}

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

public static void main(String[] args) {


Car originalCar = new Car("Toyota", 2021);
Car copiedCar = new Car(originalCar); // Creating a copy using the copy
constructor

originalCar.displayInfo();
copiedCar.displayInfo();
}
}

In this example, copiedCar is created as a copy of originalCar using the copy constructor. Both cars will
have the same model and year values.

You might also like