0% found this document useful (0 votes)
6 views

Java OOPS 1

The document explains the concept of classes and objects in Java, highlighting the structure of a class and the role of the 'new' keyword for object creation. It discusses inner classes, constructors, and the differences between stack and heap memory, as well as the use of wrapper classes for primitive types. Additionally, it covers the final keyword's implications on variable assignment and object state modification.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java OOPS 1

The document explains the concept of classes and objects in Java, highlighting the structure of a class and the role of the 'new' keyword for object creation. It discusses inner classes, constructors, and the differences between stack and heap memory, as well as the use of wrapper classes for primitive types. Additionally, it covers the final keyword's implications on variable assignment and object state modification.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

In Java, a class is a blueprint for creating objects.

It defines the properties (also called fields or


attributes) and behaviors (called methods) that the objects created from the class will have.
-----------------------------------------------------------------------------------------------------------------------------
public class Main1
{
public static void main(String[] args)
{
Car ferrari = new Car();
ferrari.brand = "Ferrari";
ferrari.color = "blue";
ferrari.speed= 90;
}
class Car{
String brand; String color; int speed;
}
}
What is wrong in this code ?

1. Class Car is inside the Main1 class:


○ The Car class is defined as an inner class of Main1. In Java, an inner class
requires an instance of the outer class (Main1) to be instantiated, but here
you're trying to create an object of Car without an instance of Main1.
2. If you want Car to be used independently, it should be declared as a separate
class or marked as static within the Main1 class.

Correct code :

When you have an inner class, it's like a class living inside another class (the outer class). The
inner class is tied to the outer class because it can directly access the outer class's data.

Think of it like this:


Imagine you have a house (the outer class) and a room (the inner class) inside it. You cannot
enter the room (create the inner class object) without first entering the house (creating the outer
class object), because the room is a part of the house.

Why do you need the outer class's instance?

When you create an instance of the outer class (the "house"), you're setting up the whole
structure, including the inner class (the "room"). Without creating the outer class first, the inner
class has no "house" to be inside.

—-----------------------------------------------------------------------------------------------------------------------------

The new keyword in Java is used to create objects (instances) of a class.

Why do we need new?

1. Dynamic Memory Allocation: When you create an object, Java needs to reserve
space in the memory for it. The new keyword tells Java to create that space.
○ For example, if you create an object of Car, Java needs to make space for
all the properties (like brand, color, speed) and the methods that belong
to that specific car object.

Initialization: The new keyword also runs the constructor of the class. A
constructor is a special method that initializes the object, setting up its initial
state.

● Without the new keyword, the constructor wouldn't run, and the object wouldn't be
properly set up.

The code works even though you haven't explicitly defined constructors for Main1 and
Car, because Java provides default constructors for classes when you don't define any.

What is a default constructor?

A default constructor is an implicit constructor that Java automatically creates for a class
if you don't explicitly define one. The default constructor:

● Has no parameters.
● Does nothing other than creating the object and allocating memory for it.

—-----------------------------------------------------------------------------------------------------------------------------

A constructor : Unlike regular methods, constructors do not have a return type, not even
void.

Types of Constructors:
● Default Constructor: If you don't define any constructor in a class, Java provides a
default constructor. This constructor takes no arguments and assigns default
values to the object's fields.
● Parameterized Constructor: You can create a constructor with parameters to
initialize the object with specific values at the time of creation.

Car() {

model = "Unknown";

year = 2020;

// Parameterized constructor

Car(String model, int year) {

this.model = model;

this.year = year;

—-----------------------------------------------------------------------------------------------------------------------------

In Java, the this keyword is a reference to the current object of the class. It is used
within an instance method or constructor to refer to the object on which the method or
constructor is being invoked.

Referring to Instance Variables: this is often used to distinguish between instance


variables (fields) and method/constructor parameters when they have the same name.
Calling Another Constructor in the Same Class: You can use this() to call one
constructor from another constructor in the same class. This is called constructor
chaining

—-----------------------------------------------------------------------------------------------------------------------------

Constructor overloading in Java refers to having more than one constructor in a class
with different parameter lists. Each constructor can perform different initialization tasks
based on the arguments provided when the object is created. Java differentiates between
constructors based on the number and types of parameters.

By providing multiple constructors, you give flexibility in how objects of the class can be
created.

Same Name: All constructors have the same name as the class.

Different Parameters: Each constructor must have a different set of parameters (either in
number, type, or both).

Constructor Overloading: Allows creating objects in different ways, depending on what


data is available at the time of object creation.
Why is the constructor and class name the same ?

In Java, the constructor and the class name are the same because the constructor is
designed to initialize an object of that specific class. This naming convention serves a
clear purpose and aligns with the concept of object-oriented programming, making it
intuitive for developers to understand that the constructor is related to the class it's a
part of.

No, in Java, you cannot use a different name for a constructor. The constructor must
have the same name as the class. This is a fundamental rule of the language.

—-----------------------------------------------------------------------------------------------------------------------------

why don't we use new keyword for primitives ?

Primitive Types: Primitive data types are stored directly in the stack memory, which is
faster and more efficient for basic data types. When you declare a primitive, the memory
is immediately allocated, and the value is stored in that location.

Objects: Objects are more complex and are stored in the heap memory. The new keyword
is used to allocate memory for objects in the heap. This allocation requires more
resources and is slightly slower than stack allocation.

The stack and heap are two different types of memory used in Java (and many other
programming languages) for storing data, but they are used in different ways and have
distinct characteristics.

1. Stack Memory:

The stack is used for storing:

● Local variables (including primitive data types and references to objects).


● Method calls (including parameters, return addresses, and local variables).
● It operates in a Last In, First Out (LIFO) manner, meaning that data is added
(pushed) and removed (popped) in a specific order, which is highly efficient.

Static: Memory for variables is allocated at compile time and released when the method
execution ends.

Automatic: Managed automatically by the system when a function is called or returns.

2. Heap Memory:

The heap is used for:

● Dynamically allocated memory—objects and arrays.


● Object instances created using the new keyword.
● All Java objects live in the heap, and memory for objects is managed by the Java
Garbage Collector.
Aspect Stack Memory Heap Memory

Usage Stores local variables, method calls, Stores objects and arrays
and references to objects. created with new.

Memory Static, automatic allocation during Dynamic allocation at runtime.


Allocation method execution.

Memory Deallocated automatically when Managed by the Garbage


Deallocation methods return. Collector.

Lifetime Exists only during the method's Objects persist as long as


execution. references exist.

Access Speed Faster due to smaller size and LIFO Slower because of larger size
structure. and complexity.

Memory Limit Small and fixed for each thread. Larger, but can lead to
OutOfMemoryError if
exceeded.

Error Types StackOverflowError due to deep OutOfMemoryError if heap


recursion or too many method calls. memory is exhausted.

Sharing Each thread has its own stack. Heap memory is shared across
all threads.

—-----------------------------------------------------------------------------------------------------------------------------

In Java, wrapper classes are object representations of the primitive data types. They
provide a way to treat primitive types as objects, which is useful in situations where you
need objects instead of primitives (e.g., in Java Collections like ArrayList, which only
work with objects, not primitives).

byte → Byte

short → Short

int → Integer

long → Long

float → Float

double → Double

char → Character

boolean → Boolean

Integer.parseInt(String): Converts a string to an int.

Double.valueOf(String): Converts a string to a Double.

Boolean.valueOf(String): Converts a string to a Boolean.

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

Float.compare(float, float): Compares two float values.

—-----------------------------------------------------------------------------------------------------------------------------

A final variable can be assigned only once. Once it is assigned a value, that value
cannot be changed.

● For primitives, the value cannot be changed.


● For objects, the reference cannot be changed, but the object's internal state can
still be modified (unless its internal fields are also declared final).

When we say that the object's internal state can still be modified for a final reference,
we mean that while the reference to the object itself cannot be changed, the properties or
fields of that object can be altered.
final Car car: The variable car is declared as final, meaning you cannot reassign
car to reference another Car object (e.g., car = new Car("BMW"); would cause an
error).

Modifying Internal State: However, you can change the internal state of the Car object
itself, such as its model field. In the example, we change the model from "Tesla" to
"Ford".

—-----------------------------------------------------------------------------------------------------------------------------

You might also like