Notifications
Clear all
Topic starter 01/08/2025 11:54 pm
Java classes are the cornerstone of object-oriented programming in Java—they’re like blueprints for creating objects that combine state (fields) and behavior (methods).
🧱 Basic Class Structure
public class Dog {
String name;
String breed;
// Constructor
public Dog(String name, String breed) {
this.name = name;
this.breed = breed;
}
// Method
public void speak() {
System.out.println(name + " says woof!");
}
}
- Fields (
name
,breed
) hold data - Constructor initializes the object when it’s created
- Methods define behavior
🐾 Creating an Object
Dog myDog = new Dog("Fido", "Labrador");
myDog.speak(); // Fido says woof!
- Use
new
to create an instance (object) of the class
🔐 Access Modifiers
Java uses modifiers to control visibility:
Modifier | Access Scope |
---|---|
public |
Accessible everywhere |
private |
Only within the class |
protected |
Within the same package or subclass |
default | (no keyword) Within the same package |
🧬 Inheritance
Classes can inherit properties and methods:
public class Puppy extends Dog {
public void play() {
System.out.println(name + " is playing!");
}
}
extends
allowsPuppy
to inherit fromDog
💡 Other Features
- Static members: Belong to the class, not the instance
- Abstract classes: Can’t be instantiated directly—used as base classes
- Interfaces: Define contracts that a class must implement
- Encapsulation: Use private fields and public getters/setters
public class Cat {
private String mood;
public String getMood() {
return mood;
}
public void setMood(String mood) {
this.mood = mood;
}
}