Forum

Learn Java Classes
 
Notifications
Clear all

Learn Java Classes

1 Posts
1 Users
0 Reactions
14 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

 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 allows Puppy to inherit from Dog

💡 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;
    }
}

 


   
Quote
Share: