Introduction to Classes & Objects
Prerequisites: Method overloading
A class is a blueprint describing a kind of thing; an object is a specific instance created from that blueprint.
Syntax
class Dog {
String name;
int age;
void bark() {
System.out.println(name + " says Woof!");
}
}
Example
Dog myDog = new Dog();
myDog.name = "Rex";
myDog.age = 3;
myDog.bark();
Expected output
Rex says Woof!
Real-world analogy: a class is like a cookie cutter, and each object is a cookie made from it — every cookie has the same shape (fields and methods), but its own specific values.
Common mistakes
- Forgetting
newwhen creating an object —Dog myDog;only declares a variable that can hold aDog; it doesn't create one.
Practice
Create a Cat class with a name field and a meow() method that
prints "<name> says Meow!", then create and use one.
Show solution
class Cat {
String name;
void meow() {
System.out.println(name + " says Meow!");
}
}
Cat myCat = new Cat();
myCat.name = "Whiskers";
myCat.meow();