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 Java Basics Perfecting the Prototype Conditional ints

Ting-Chieh Huang
Ting-Chieh Huang
3,387 Points

Java inheritance (overloading methods in subclass over super class)

I remember we are allowed to overload and override methods in subclass. But why this code (overload) doesn't work?

class practice{
    public static void main(String args[]){

        Bar Treehouse[] = new Bar[2];

        Treehouse[0]=new Baz();
        Treehouse[0].doBar(3); //this one works
        Treehouse[0].doBar(3,4);  // why this one doesn't work?
    }



}


 class Bar {
      public void doBar(int x) {
          System.out.println("this is dobar"+ x);
          }
      }




    class Baz extends Bar {
      public void doBar(int x, double y) {
          System.out.println("x and y"+ x +" "+y);
      }
    }

1 Answer

Dan Johnson
Dan Johnson
40,533 Points

When you overload a method, it's basically creating an entirely new method with no direct association with the other of the same name, it's the signature that matters. So in your example doBar with two arguments only is known by the sub class.

Here's an example of overriding a method:

public class Application {
    public static void main(String[] args) {
        Super[] examples = {new Super(), new Sub()};

        examples[0].overriding();
        examples[1].overriding();
    }
}

class Super { 
    public void overriding() {
        System.out.println("Super class");
    }
}

class Sub extends Super {
    // Notice the equivalent function signatures.
    @Override
    public void overriding() {
        System.out.println("Sub class");
    }
}

Note that the @Override annotation isn't required, but it'll help you catch logic errors if you don't match up the function signatures.