Java Programming Day 11

HimanshiHimanshi
5 min read

🌟 Java Day 11 β€” Diving Deep into Object-Oriented Concepts

πŸ“Œ Introduction

Welcome to Day 11 of my Java journey! Today, I explored fundamental but powerful OOP concepts essential in Java programming: super keyword, .toString() method, and method overriding. These concepts help write flexible, readable, and maintainable code. I practiced modifying example programs and share detailed explanations and outputs below.


🧠 Concepts Covered Today

  • super keyword

  • .toString() method

  • Method Overriding

  • Real-world examples

  • Differences between inheritance and overriding

  • Importance of overriding in polymorphism


πŸ’‘ Topic 1: super Keyword in Java

πŸ”Ž What is super?

  • Refers to the immediate parent class of a class.

  • Used to access parent class methods, constructors, and fields.

βœ… Program: Using super in Java

javaCopyEdit// Parent class
class Person {
    String firstName;
    String lastName;

    Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    void showName() {
        System.out.println("Name: " + firstName + " " + lastName);
    }
}

// Subclass
class Student extends Person {
    double cgpa;

    Student(String firstName, String lastName, double cgpa) {
        super(firstName, lastName);  // calling parent constructor
        this.cgpa = cgpa;
    }

    void display() {
        super.showName();  // calling parent method
        System.out.println("CGPA: " + cgpa);
    }
}

// Another subclass
class Employee extends Person {
    String department;

    Employee(String firstName, String lastName, String department) {
        super(firstName, lastName);
        this.department = department;
    }

    void display() {
        super.showName();
        System.out.println("Department: " + department);
    }
}
javaCopyEditpublic class Main {
    public static void main(String[] args) {
        Student student = new Student("Harry", "Porter", 8.7);
        student.display();

        Employee employee = new Employee("Tom", "Riddle", "Finance");
        employee.display();
    }
}

πŸ” Explanation

  • super(firstName, lastName) calls the constructor of the Person class.

  • super.showName() calls the showName() method of the parent class to reuse code.

  • This allows subclasses to inherit and extend parent class functionality cleanly.


πŸ’‘ Topic 2: .toString() Method

πŸ”Ž What is .toString()?

  • Method from Object class (superclass of all Java classes).

  • Returns a string representation of an object.

  • Default toString() returns a hashcode string, e.g., Car@3e25a5.

  • Overriding it provides meaningful information about the object.

βœ… Program: Overriding .toString()

javaCopyEditclass Car {
    String brand;
    String model;
    int year;
    String color;

    Car(String brand, String model, int year, String color) {
        this.brand = brand;
        this.model = model;
        this.year = year;
        this.color = color;
    }

    // Overriding toString method to provide meaningful output
    @Override
    public String toString() {
        return "Car [Brand=" + brand + ", Model=" + model + ", Year=" + year + ", Color=" + color + "]";
    }
}

public class Main {
    public static void main(String[] args) {
        Car car1 = new Car("Ford", "Mustang", 2025, "Red");
        Car car2 = new Car("Chevrolet", "Corvette", 2026, "Blue");

        // Printing object calls toString() automatically
        System.out.println("Car 1 details: " + car1);
        System.out.println("Car 2 details: " + car2);
    }
}

πŸ” Explanation

  • Overriding .toString() shows car details in a human-readable format.

  • Printing objects directly calls .toString() implicitly.

  • Helpful for debugging and logging to see meaningful data instead of default hash codes.


πŸ’‘ Topic 3: Method Overriding

πŸ”Ž What is Method Overriding?

  • When a subclass provides its own implementation of a method defined in its superclass.

  • The method signature (name, return type, parameters) must be the same.

  • Supports runtime polymorphism β€” the subclass version is invoked dynamically.

βœ… Program: Method Overriding Example

javaCopyEdit// Parent class
class Animal {
    void move() {
        System.out.println("This animal is running");
    }
}

// Subclasses
class Dog extends Animal {
    // inherits move() method
}

class Cat extends Animal {
    // inherits move() method
}

class Fish extends Animal {
    @Override
    void move() {
        System.out.println("This animal is swimming");
    }
}

// Main class to test behavior
public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();
        Fish fish = new Fish();

        System.out.println("Dog's movement:");
        dog.move();  // prints "This animal is running"

        System.out.println("Cat's movement:");
        cat.move();  // prints "This animal is running"

        System.out.println("Fish's movement:");
        fish.move(); // prints "This animal is swimming"
    }
}

πŸ” Explanation

  • Dog and Cat inherit move() from Animal.

  • Fish overrides move() to provide unique behavior.

  • Demonstrates polymorphism where method behavior depends on object type.


πŸ“˜ Key Takeaways

ConceptSummary
superAccesses parent class constructors, methods, and fields.
.toString()Returns human-readable string for objects; overridden to customize output.
Method OverridingSubclass provides its own version of a superclass method to change behavior at runtime.
InheritanceEnables code reuse and hierarchy between classes.
PolymorphismAchieved through method overriding, allowing dynamic method calls.

🧠 Quick Comparison: super vs this

KeywordRefers toUsage
superImmediate parent classCall parent methods or constructors
thisCurrent class objectAccess current object's fields and methods

βœ… Why These Concepts Matter

  • super helps reuse and extend existing class logic.

  • .toString() improves debugging and logging clarity.

  • Method overriding enables polymorphism, making code flexible and scalable.


🎯 Conclusion

Day 11 deepened my understanding of Java’s OOP core β€” super, .toString(), and method overriding. These concepts are key to managing complexity by promoting code reuse, customization, and dynamic behavior. Mastering them makes Java programming robust and maintainable.

2
Subscribe to my newsletter

Read articles from Himanshi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Himanshi
Himanshi

Hi! I'm a curious and self-driven programmer currently pursuing my BCA πŸŽ“ and diving deep into the world of Java β˜• from Day 1. I already have a foundation in programming, and now I'm expanding my skills one concept, one blog, and one project at a time. I’m learning Java through Bro Code’s YouTube tutorials, experimenting with code, and documenting everything I understand β€” from basic syntax to real-world applications β€” to help others who are just starting out too. I believe in learning in public, progress over perfection, and growing with community support. You’ll find beginner-friendly Java breakdowns, hands-on code snippets, and insights from my daily coding grind right here. πŸ’‘ Interests: Java, Web Dev, Frontend Experiments, AI-curiosity, Writing & Sharing Knowledge πŸ› οΈ Tools: Java β€’ HTML/CSS β€’ JavaScript β€’ Python (basics) β€’ SQL 🎯 Goal: To become a confident Full Stack Developer & AI Explorer πŸ“ Based in India | Blogging my dev journey #JavaJourney #100DaysOfCode #CodeNewbie #LearnWithMe