Basic Object-Oriented Concepts: Classes and Objects
Class definition, object instantiation, constructors, and instance methods in Java.
Classes and Objects
A class is a blueprint that defines attributes and methods. An object is a concrete instance of a class, created with the new keyword.
ClassName obj = new ClassName();
Constructors
Constructors are special methods that initialize an object when it is created.
- Default constructor — No parameters, assigns default values.
- Parameterized constructor — Accepts arguments to initialize fields.
- Constructor overloading — Multiple constructors with different parameter lists.
The this Keyword
this refers to the current object instance. It is commonly used to:
- Distinguish instance variables from parameters with the same name.
- Call another constructor from within a constructor.
Instance Methods
Instance methods operate on the data of a specific object and are called on an object reference.
Example
// StudentDemo.java
// Demonstrates class, constructors, and methods in Java.
class Student {
// Instance variables
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
// Method to display student info
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class StudentDemo {
public static void main(String[] args) {
// Create students using both constructors
Student s1 = new Student();
Student s2 = new Student("Alice", 20);
s1.display();
s2.display();
}
}
Full source:
examples/05-classes-objects/StudentDemo.java