Sobes.tech
Junior

Can you override a method in Java? What about a constructor?

sobes.tech AI

Answer from AI

Yes, the method can be overridden. This is called overriding and is used to implement polymorphism at runtime.

Method overriding: a subclass provides its own implementation of a method that is already defined in its superclass. The method must have the same signature (name, number and types of parameters, order of parameters).

class Animal {
    public void makeSound() {
        // Default implementation
        System.out.println("Some generic sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        // Overridden implementation
        System.out.println("Woof");
    }
}

Constructors cannot be overridden. Constructors are not regular methods. They do not have a return type, and their name always matches the class name. Each class has its own constructors used for initializing objects of that class.

If you need to call the superclass constructor from a subclass, use the super() keyword.

class Animal {
    String species;

    public Animal(String species) {
        this.species = species;
        System.out.println("Creating an animal of species: " + this.species);
    }
}

class Dog extends Animal {
    String breed;

    public Dog(String species, String breed) {
        super(species); // Call to superclass constructor
        this.breed = breed;
        System.out.println("Creating a dog of breed: " + this.breed);
    }
}
Can you override a method in Java? What about a… - sobes.tech