Java Tutorial
Classes and Object-Oriented Programming
Learn classes, objects, constructors, encapsulation, inheritance and polymorphism.
Concept
A class describes the state and behavior of objects. Constructors initialize new instances, while access modifiers help control which state is visible outside the class.
Inheritance can reuse behavior, but composition is often clearer when one object simply contains or collaborates with another. Polymorphism lets code depend on common contracts rather than concrete implementation details.
Example
class Student {
private String name;
Student(String name) {
this.name = name;
}
String getName() {
return name;
}
}
Type the example yourself and change at least one value. Small experiments reveal syntax and behavior faster than passive reading.
Practice Tasks
- Create a Course class with private fields.
- Add a constructor and getters.
- Create a subclass and override one method.
Key Takeaways
- Encapsulation protects object state.
- Constructors initialize objects.
- Use inheritance when there is a real is-a relationship.
Previous
← Methods and Arrays
← Methods and Arrays