-1

In this code

class Foo {

    public int a = 3;
}

class Bar extends Foo {

    public int a = 8;
}

public class HelloWorld {

    public static void main(String[] args) {
        Foo f = new Bar();
        Bar f = new Bar();
    }
}

What is the difference between

Foo f = new Bar(); 

and

Bar f = new Bar();

Thank You

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Karthik Rao V
  • 61
  • 1
  • 7
  • The first instantiation is more broad than the second. A `Bar` is a `Foo`, but a `Foo` may not be a `Bar`. – Tim Biegeleisen Jun 20 '16 at 08:20
  • 1
    Hint: this is very basic stuff. Please do some prior research on such topics **in advance**. Stackoverflow is not programming school where you turn to to be **teached** stuff that is documented all over the place. – GhostCat Jun 20 '16 at 08:24
  • Sorry I am a beginner. Please do provide me the link to the reading material for this topic. Thank You. @Jägermeister – Karthik Rao V Jun 20 '16 at 08:25
  • @Jägermeister you are correct, but do not forget that we all begun from somewhere... – Sir. Hedgehog Jun 20 '16 at 08:25
  • You can start with: https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) and take a look this picture: https://en.wikipedia.org/wiki/File:Multilevel_Inheritance.jpg . I do agree with the comments from @Jägermeister. – Alex Jun 20 '16 at 08:28

1 Answers1

1

This relationship is called the is-a relationship. Every Bar object is a Foo object. However, a Foo object cannot be a Bar object.

When you call Foo f = new Bar(), You are creating a Foo object, which means that only the fields of Foo are accessible in f. That is, f.a in this case is 3.

On the other hand, Bar f = new Bar() creates a Bar object, which means that f.a will give you 8 in this case.

Omar El Halabi
  • 2,118
  • 1
  • 18
  • 26