Anatomy of a Class | Constructors | Accessor Methods | Mutator Methods | Code Example | Hacks | Quiz |
Unit 5 - Writing Classes Examples
Writing Classes Examples
Primitive Types Example
// Define a class named Person
class Person {
// Attributes of the Person class
String name;
int age;
String address;
// Constructor to initialize Person objects
Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// Method to display the details of the person
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
// Method to calculate the birth year based on age
int calculateBirthYear() {
int currentYear = 2024;
return currentYear - age;
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Person class
Person person1 = new Person("Alice", 30, "123 Main St, Springfield");
// Call methods on the object
person1.displayDetails();
int birthYear = person1.calculateBirthYear();
System.out.println("Birth Year: " + birthYear);
}
}
Main.main(null);
Refrence Types Example
// Base class Animal
class Animal {
// Attribute of the Animal class
String name;
// Constructor to initialize Animal objects
Animal(String name) {
this.name = name;
}
// Method to make the animal speak
void speak() {
System.out.println(name + " makes a sound.");
}
}
// Subclass Dog that inherits from Animal
class Dog extends Animal {
// Constructor to initialize Dog objects
Dog(String name) {
super(name); // Call the constructor of the superclass
}
// Overridden method to make the dog speak
@Override
void speak() {
System.out.println(name + " barks.");
}
// Method specific to the Dog class
void fetch() {
System.out.println(name + " is fetching the ball!");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the Animal class
Animal genericAnimal = new Animal("Generic Animal");
genericAnimal.speak(); // Output: Generic Animal makes a sound.
// Create an object of the Dog class
Dog dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
dog.fetch(); // Output: Buddy is fetching the ball!
}
}
Main.main(null);