Classes & OOP
Object-oriented programming
Introduction
In this lesson, you'll learn about classes & oop in Java. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with object-oriented programming.
Java has its own approach to object-oriented programming, which we'll explore step by step.
The Java Way
Let's see how Java handles this concept. Here's a typical example:
public abstract class Animal {
private String name; // private field
public Animal(String name) {
this.name = name;
}
public String getName() { return name; } // getter
public abstract String speak(); // must override
}
public class Dog extends Animal {
public Dog(String name) { super(name); }
@Override
public String speak() {
return getName() + " barks.";
}
}
Dog d = new Dog("Rex");
System.out.println(d.speak());Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
class Animal {
#name; // private field
constructor(name) {
this.#name = name;
}
get name() { return this.#name; }
speak() {
return this.#name + " makes a sound.";
}
}
class Dog extends Animal {
constructor(name) { super(name); }
speak() {
return this.name + " barks.";
}
}
const d = new Dog("Rex");
console.log(d.speak());You may be used to different syntax or behavior.
Java uses public/private/protected keywords; JS uses # for private
You may be used to different syntax or behavior.
Java abstract classes cannot be instantiated; JS has no abstract keyword
You may be used to different syntax or behavior.
Java uses getter methods by convention; JS has get/set syntax
You may be used to different syntax or behavior.
@Override annotation documents intent; JS has no equivalent
Step-by-Step Breakdown
1. Access Modifiers
Java uses explicit public/private/protected keywords for access control. JS uses # for private fields.
#name; // JS privateprivate String name; // Java private2. Abstract Classes
Java abstract classes define a contract that subclasses must fulfill. In JS you'd throw an error in the base method.
public abstract String speak(); // subclass MUST implement3. @Override
The @Override annotation tells the compiler to verify this method actually overrides a parent method — catching typos.
speak() { return "barks"; } // no check in JS@Override
public String speak() { return getName() + " barks."; }Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Java uses public/private/protected keywords; JS uses # for private
- Java abstract classes cannot be instantiated; JS has no abstract keyword
- Java uses getter methods by convention; JS has get/set syntax
Key Takeaways
- JS # private → Java private keyword
- Java abstract enforces method implementation
- @Override documents and verifies overrides
- Java getters are methods by convention (getName)