Class ✔
Class
A java class is a group of values with a set of operations to manipulate this values. It is a blueprint for creating objects. A class encapsulates data for the object and methods to manipulate that data. It is use to define a new data type(primitive).
Attributes
Variables and methods used in the class are called attributes/fields. Attributes are accessed by creating an object of the class and dot notation.
A class contains following members:
- Instance Variables
- Methods
- Constructor
Instance Variable
Variable defined within a class are called instance variables because each instance of the class(that is, each object of the class) contains its own copy of these variable.
Object
It represent an instance of a class. It's a runtime entity that holds the state and behaviour of a class. Object is a class type variable. When you create a class, you are creating a new data type. And you can use this data type by declaring objects of this data type.
Each time you create an object of a class, a copy of each instance variables is created except static varible, its create only once.
Objects are create using the new keyword. Each object is stored at a unique memory location.
Create Object:
Box myBox; // reference
myBox=new Box(); // allocate
new Operator
It is used to create new objects
- allocates memory for the object on the heap
- initializes the object by calling its constructor
- returns a reference to that memory which is used to access the object's methods and attributes.
Constructor
A class contructor if defined is called whenever a program creates an object of that class. It is invoked directly when an object is created and before new operator execute completely.
It doesn't have any return type, not even void and hence can't return any values. It is used to initialize objects. It is called when an instance of a class is created, and it usually sets initial values for the objects attributes.
It doesn't inherited as it's not part of class member.
Types:
- default constructor
- parameterized constructor
Default Constructor
A default constructor is automatically provided by the java compiler if no constructors are explicitly defined in a class. It initializes object fields with default value(null, 0).It has the same access modifier as the class.
Parameterized Constructor
A parameterized constructor accepts parameters, allowing you to initialize the objects fields with specific values at the time of creation.
Constructor Chaining
It refers to the process of calling one constructor from another within the same/different class. It is used to reduce code duplication and ensure proper initialization.
Each class calls the constructor of its parent class when it is instantiated, leading to a chain of constructor calls. Constructor doesn't inherited as it's not part of the class member. But in every inheritance constructor of parent class will be called, which result constructor chaining.
class SuperParent{
SuperParent(){
System.out.println("I'm Super Parent");
}
SuperParent(int x){
System.out.println("I'm Super Parent with "+x);
}
}
class Parent extends SuperParent{
Parent(){
System.out.println("I'm Parent");
}
Parent(int x){
System.out.println("I'm Parent with "+x);
}
}
class Child extends Parent{
Child(){
System.out.println("I'm Child");
}
Child(int x){
System.out.println("I'm Child with "+x);
}
}
class SuperChild extends Child{
SuperChild(){
super(4);
System.out.println("I'm SuperChild");
}
SuperChild(int x){
System.out.println("I'm SuperChild with "+x);
}
}
Output:
I'm Super Parent
I'm Parent
I'm Child with 4
I'm SuperChild
Access Modifiers in Constructors
-
privateConstructor-
Objects cannot be created outside the class.
-
Only the class itself can create objects.
-
Prevents direct object creation:
// Singleton Pattern
public class Database {
private static Database instance;
private Database() { }
public static Database getInstance() {
if (instance == null) {
instance = new Database();
}
return instance;
}
}
-
-
protectedConstructor- Within the same package
- By subclasses (even in other packages)
- It cannot be accessed, by non-subclass classes outside the package
Method
Variables used in method signature are called parameter, and variables used during call are called arguments.
Parameter vs Argument
| Term | Meaning | Where Used |
|---|---|---|
| Parameter | Placeholder | In method definition |
| Argument | Actual value | In method call |
Instance method can call an instance methods directly. There is no need to use object.
Static method can only be called from a static method.
Method overloading depends on the parameter, where method overriding depends on the object.
Method Overloading
When more than one method with the same name is defined in the same class,it is known as method overloading as long as their parameter declarations are different.
Method overloading is a way to achieve static polymorphism in java.
Parameter must be differents(order, type, number), return type may or may not be differents.
Method Overriding
The ability of a subclass to re-implement an instance method inherited from a superclass is called method overriding.
- overriding method must have same argument list and return type.
- final, static, constructor method can't be overriden.
Method overriding is a way to achieve dynamic polymorphism in java.
If a method in a subclass has the same method signature as a method in its superclass, the subclass method overrides the inherited method. If a method in a subclass has the different method signature as a method in its superclass, the subclass method overloads the inherited method.
class SuperParent{
static void show(double x){
System.out.println("Super Parent");
}
}
class Parent extends SuperParent{
static void show(int x){
System.out.println("Parent");
}
}
class Test extends Parent{
public static void main(String[] args){
show(4);
show(4.5);
}
}
Question
Why only static method can be called within static method?
In languages like Java, C#, and C++, a static method belongs to the class itself, not to any object. Because of that, a static method does not have access to instance data or instance methods.
The key idea is object vs class context.
Static Methods Don't Have an Object (this)
A non-static (instance) method runs on an object.
Example in Java:
class Test {
int x = 10;
void show() { // instance method
System.out.println(x);
}
}
To call show():
Test t = new Test();
t.show();
The method internally uses this, which refers to the object t.
But a static method has no object, so this does not exist.
Static Methods Belong to the Class
Example:
class Test {
static void display() {
System.out.println("Hello");
}
}
You call it like this:
Test.display();
Notice:
- No object is created
- The method is attached to the class
Why Static Methods Can't Directly Call Instance Methods
Consider this:
class Test {
void show() {
System.out.println("Instance method");
}
static void display() {
show(); // ❌ error
}
}
Why error?
Because show() needs an object, but display() has no object.
The compiler asks:
Which object's
show()should I call?
There is no answer.
How to Fix It
Create an object inside the static method.
class Test {
void show() {
System.out.println("Instance method");
}
static void display() {
Test t = new Test();
t.show(); // ✔ valid
}
}
Now the compiler knows which object to use.
Why Static Methods Can Call Static Methods
Both belong to the class, not objects.
class Test {
static void A() {
B();
}
static void B() {
System.out.println("Hello");
}
}
Both methods are class-level, so no object is needed.
Simple Rule
| Method Type | Can Call |
|---|---|
| Static method | Static methods directly |
| Instance method | Static + Instance methods |
Easy way to remember
Static = class-level Instance = object-level
A class-level method cannot directly access object-level members because no object exists yet.