Java OOP — Classes & Objects
The foundation of every non-trivial Java program.
What is OOP?
Object-oriented programming models problems by defining types of things (classes) that have data (fields) and behavior (methods). You then create instances of those types (objects) and have them interact.
Java has four core OOP principles, sometimes called "the four pillars":
- Encapsulation — bundling data and methods, hiding internals
- Inheritance — building new classes from existing ones
- Polymorphism — one interface, many implementations
- Abstraction — exposing what something does, hiding how
Defining a class
public class Person { // Fields (instance variables) String name; int age; // Method public void introduce() { System.out.println("Hi, I'm " + name + ", " + age); } }
Creating objects (instantiation)
Use new to create an instance:
public class App { public static void main(String[] args) { Person p1 = new Person(); p1.name = "Raman"; p1.age = 28; p1.introduce(); // "Hi, I'm Raman, 28" Person p2 = new Person(); p2.name = "Aman"; p2.age = 22; p2.introduce(); // "Hi, I'm Aman, 22" } }
Each Person object has its own name and age.
Constructors
A constructor runs when you create a new object. Same name as the class, no return type:
public class Person { String name; int age; // Constructor public Person(String name, int age) { this.name = name; // 'this' refers to the object being constructed this.age = age; } public void introduce() { System.out.println("Hi, I'm " + name + ", " + age); } } // Now creation is one line: Person p = new Person("Raman", 28); p.introduce();
The this keyword
this refers to the current object. It's used when a parameter has the same name as a field, or to call another constructor in the same class.
Constructor overloading
Like methods, constructors can be overloaded:
public class Person { String name; int age; public Person() { this("Anonymous", 0); // call the other constructor } public Person(String name, int age) { this.name = name; this.age = age; } }
Static vs instance members
Instance members belong to each object. Static members belong to the class itself, shared across all instances.
public class Counter { static int totalCreated = 0; // shared by all instances int id; // unique per instance public Counter() { totalCreated++; this.id = totalCreated; } } new Counter(); new Counter(); System.out.println(Counter.totalCreated); // 2
Access static members through the class name: Math.PI, Integer.parseInt(...).