0

If I have

    public class Base{  
        public void method(){
            System.out.println("I am base");
        } 
    }

    public class Derived extends Base{  
        public void method(){
            System.out.println("I am derived");
        }  
    } 

is there a difference between

Base b = new Derived();

and

Derived d = new Derived();

? And, would

b.method();
d.method();

print the same?

Carlos
  • 121
  • 1
  • 1
  • 8
  • They would print the same. However if `Derived` contained methods that didn't exist in `Base`, then you wouldn't be able to call them. i.e. if `Derived` had `otherMethod()`, you can't do `b.otherMethod()`. – 4castle May 24 '16 at 02:17
  • @4castle, thank you. I suppose that is all the difference. – Carlos May 24 '16 at 02:26
  • In many cases it's better to do `Base b = new Derived()` though, because it allows you to easily switch to another class that extends `Base`, and it's clearer in your code that you only plan on using the methods from `Base`. For example, most people prefer `Map map = new HashMap<>()` because it allows for a quick transition to `TreeMap` later down the line. – 4castle May 24 '16 at 02:34

0 Answers0