CHAPTER-7 Java Class and Objects - Examples

In Java, a class acts as a blueprint for creating objects, defining their attributes (fields) and behaviors (methods).

Some basic Java class examples demonstrating properties (attributes/fields) and methods (behaviors) for beginners:

1. Simple Car Class.
2. Person Class with Getters and Setters.
3. Calculator Class with Basic Operations.
4. Dog Class with a speak Method.
5. Book Class with a displayInfo Method.
6. Person Class with Attributes and Methods,Constructor
7. Calculator Class with Static Methods.
8. Here is a Java class named Trip with a constructor: - Mini Project.
9. HotelBooking Class Example.
10. Company Class Example.

1. Simple Java Class Program with Car details A Class contains properties and methods. Create a Car object in the main method and call start() method.

class Car {
    // Properties (attributes)
    String color;
    String model;
    int year;

    // Method (behavior)
    void start() {
        System.out.println("Car started!");
    }
}

  
2. Simple Class with Getters and Setters. This java program uses Getter and Setterts to set and get (read) values of the properties. In the main, create a person object with the person's data name, age. Display data using get methods, and update data using set methods.

    
  class Person {
    // Properties
    String name;
    int age;

    // Constructor to initialize properties
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Methods (Getters)
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    // Method (Setter)
    public void setAge(int newAge) {
        if (newAge > 0) { // Basic validation
            this.age = newAge;
        } else {
            System.out.println("Age cannot be negative.");
        }
    }
}

    
3. Calculator Class with Basic Operations

This program gives you an idea of how to write a simple method and pass parameters to it and return a result. In the main method, create an object of Calculator and call each method with an object and print the result.


   class Calculator {
    // No properties needed for this simple calculator

    // Methods for operations
    int add(int a, int b) {
        return a + b;
    }

    int subtract(int a, int b) {
        return a - b;
    }

    double multiply(double a, double b) {
        return a * b;
    }
}

  
4. Java Class with a sounds Method This class has two properties and one method. Create an object from the Dog class in the main, and call the method sound() using with that object.

class Dog {
    // Properties
    String breed;
    String name;

    // Method
    void sounds() {
        System.out.println(name + " says Woof!");
    }
}

  
5. Book Class with a displayInfo Method This class has three properties and one method to display properties. Create a Book object, set the values (object.property=value), and call the displayInfo method.

  class Book {
    // Properties
    String title;
    String author;
    int pages;

    // Method
    void displayInfo() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
        System.out.println("Pages: " + pages);
    }
}

  
6. Person Class with Attributes and Methods,Constructor:

This example introduces fields (attributes) and methods (behaviors) within a class, demonstrating encapsulation.

public class Person {
   // Attributes
    String name;
    int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display information
    public void introduce() {
        System.out.println("Hi, my name is " + name + " and I am " + age + " years old.");
    }

    public static void main(String[] args) {
        Person person1 = new Person("Alice", 30);
        person1.introduce();
    }
}

  
  
7. Calculator Class with Static Methods: This class demonstrates static methods, which belong to the class itself rather than to an instance of the class. Static methods are called directly with the Classname. No need to create an object.

  public class Calculator {
    public static int add(int a, int b) {
        return a + b;
    }

    public static int subtract(int a, int b) {
        return a - b;
    }

    public static void main(String[] args) {
        int sum = Calculator.add(10, 5);
        System.out.println("Sum: " + sum);
        int difference = Calculator.subtract(10, 5);
        System.out.println("Difference: " + difference);
    }
}

  
8. Here is a Java class named Trip with a constructor: - Mini Project

	     
  public class Trip {
    private String destination;
    private int numberOfTravelers;
    private double budgetPerPerson;

    // Constructor for the Trip class
    public Trip(String destination, int numberOfTravelers, double budgetPerPerson) {
        this.destination = destination;
        this.numberOfTravelers = numberOfTravelers;
        this.budgetPerPerson = budgetPerPerson;
    }

    // Getter methods (optional, but good practice for accessing private fields)
    public String getDestination() {
        return destination;
    }

    public int getNumberOfTravelers() {
        return numberOfTravelers;
    }

    public double getBudgetPerPerson() {
        return budgetPerPerson;
    }

    // Method to calculate total trip cost
    public double calculateTotalCost() {
        return numberOfTravelers * budgetPerPerson;
    }

    public static void main(String[] args) {
        // Creating a Trip object using the constructor
        Trip myTrip = new Trip("Paris", 2, 1500.00);

        // Accessing information and calling methods
        System.out.println("Destination: " + myTrip.getDestination());
        System.out.println("Number of Travelers: " + myTrip.getNumberOfTravelers());
        System.out.println("Budget per Person: $" + myTrip.getBudgetPerPerson());
        System.out.println("Total Trip Cost: $" + myTrip.calculateTotalCost());
    }
}
  
Explanation:
  • public class Trip: This declares a public class named Trip.
  • private String destination;, private int numberOfTravelers;, private double budgetPerPerson; : These are instance variables (fields) that store information about a Trip object. They are declared as private to encapsulate the data.
  • public Trip(String destination, int numberOfTravelers, double budgetPerPerson) : This is the constructor for the Trip class.
  • It has the same name as the class (Trip).
  • It takes three parameters: destination (String), numberOfTravelers (int), and budgetPerPerson (double).
  • this.destination = destination; : This line assigns the value passed in the destination parameter to the destination instance variable of the current Trip object. this refers to the current object.
  • Getter Methods (getDestination(), getNumberOfTravelers(), getBudgetPerPerson()) : These public methods allow controlled access to the private instance variables.
  • calculateTotalCost() :
  • This method demonstrates a behavior of the Trip object, calculating the total cost based on the number of travelers and budget per person.
  • main method: This is a simple example of how to create a Trip object using the constructor and then interact with it.
Java hotel booking class example with method overloading - Mini Project

Method overloading is a core Java concept where multiple methods in the same class share the same name but have different parameters (different number, type, or order of parameters). In a hotel booking context, this allows a bookRoom method to handle various booking scenarios with a single, intuitive method name.

9. HotelBooking Class Example

This example demonstrates method overloading for different booking options (e.g., by room number, by room type, or with specific dates) within a HotelBooking class.




public class HotelBooking {

    // Method 1: Book by room number
    public void bookRoom(int roomNumber) {
        System.out.println("Booking a room by number: " + roomNumber);
        // Logic to find the room and book it
        System.out.println("Status: Room " + roomNumber + " is booked.");
    }

    // Method 2: Overloaded to book by room type (e.g., "Suite", "Standard")
    // Different parameter type: String instead of int
    public void bookRoom(String roomType) {
        System.out.println("Searching for an available room of type: " + roomType);
        // Logic to find the first available room of the specified type and book it
        System.out.println("Status: An available " + roomType + " room is booked.");
    }

    // Method 3: Overloaded to book with dates and guest name
    // Different number of parameters: 3 parameters instead of 1
    public void bookRoom(String guestName, String checkInDate, String checkOutDate) {
        System.out.println("Booking for guest: " + guestName);
        System.out.println("Check-in: " + checkInDate + ", Check-out: " + checkOutDate);
        // Logic for date-specific booking
        System.out.println("Status: Booking confirmed for the specified dates.");
    }

    // Method 4: Overloaded to book a specific room number with the guest's name
    // Different number and order of parameters: int, String
    public void bookRoom(int roomNumber, String guestName) {
        System.out.println("Booking room " + roomNumber + " for guest: " + guestName);
        // Specific booking logic
        System.out.println("Status: Room " + roomNumber + " booked for " + guestName);
    }

    public static void main(String[] args) {
        HotelBooking bookingSystem = new HotelBooking();

        System.out.println("--- Initiating Bookings ---");
        // Calls Method 1 (int roomNumber)
        bookingSystem.bookRoom(101);

        // Calls Method 2 (String roomType)
        bookingSystem.bookRoom("Suite");

        // Calls Method 3 (String guestName, String checkInDate, String checkOutDate)
        bookingSystem.bookRoom("Alice", "2025-12-01", "2025-12-05");

        // Calls Method 4 (int roomNumber, String guestName)
        bookingSystem.bookRoom(205, "Bob");
    }
}

   
Explanation of Overloading:
  • The Java compiler determines which bookRoom method to call based on the arguments provided at compile time (a process known as static or compile-time polymorphism):
  • bookingSystem.bookRoom(101);: Matches the method signature with a single int parameter.
  • bookingSystem.bookRoom("Suite");: Matches the method signature with a single String parameter.
  • bookingSystem.bookRoom("Alice", ...);: Matches the method signature with three String parameters.
  • bookingSystem.bookRoom(205, "Bob");: Matches the method signature with an int and a String parameter.
10. Basic Company Class Example

This example defines a Company class with attributes like companyName and established, along with a methods aboutCompany(),services() to display company information and its service.
This class can be further refined with concepts like an Employee class or additional methods.


 
 public class Company {
    // Attributes (fields)
    String companyName;
    int established;

    // Constructor to initialize the object
    public Company(String companyName, int established) {
        this.companyName = companyName;
        this.established = established;
    }

    // Method to display company information (behavior)
    public void aboutCompany() {
        System.out.println("Company Name: " + companyName);
        System.out.println("Founded In: " + established);
    }
    
        // Method to display company information (behavior)
    public void services() {
        System.out.println("Software Development ");
       }

    // Main method (entry point) to create and use the Company object
    public static void main(String[] args) {
        // Create an object of the Company class
        Company myCompany = new Company("XyzTech Solutions Inc.", 2010);

        // Call the displayInfo method to show the details
        myCompany.aboutCompany();
        myCompany.services();
    }
}