Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Could you just override the method instead of making a constructor?

class Animal { String sound = "";

void makeSound () {
    System.out.println(sound);
}

}

class Dog extends Animal { @Override void makeSound() { super.makeSound(); System.out.println("Bark"); }

2 Answers

Tonnie Fanadez
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 Points

Overriding allows a subclass to provide an implementation of a method that is already declared on the superclass. Constructors are used for initializing Objects. So, in this case, @Override is the one applicable. See my code below.

class Animal { 

String sound = "";

//constructor t= intialize String sound variable
public Animal(String sound){
this.sound = sound;
}

//superclass  method
public void makeSound () {
    System.out.println(sound);
}
}

class Dog extends Animal { 
@Override 
public void makeSound() { 
super.makeSound(); 

//inner classes can access variable from the outer class
System.out.println(sound);
}
}

Thanks. Now I understand