-7
public class Top{ 
    public int top = 1;
    public Top(int top){ this.top = top; }
}
public class Middle extends Top{
    public Middle(int top){
        super(top);
        this.top = this.top + top;
    }
}
public class Bottom extends Middle{
    public Bottom(){ super(3); }
    public Bottom(int top){
        super(top);
        this.top = top;
    }
}

For this class, I'm confused as to why Top t = new Top() is a invalid declaration? Does it have to have a passing argument for this object t being created to be valid?

Why is 1) Top t = new Bottom() and 2) Top t = new Top(3) valid? I'm new to java and Does the bottom class have an empty constructor so 1) is valid?

Also, say for example Top t = new Middle(2), how would I proceed to figure out what t.top without using code? Like the dot operator always throws me off, what I'm thinking is that the object "t" is being associated with the attributes of the top variable? It's supposed to equal 4 but I'm trying to figure this out but these concepts seem so foreign to me right now. Any explanation would be appreciated.

kapex
  • 28,903
  • 6
  • 107
  • 121
Toby
  • 131
  • 7
  • 3
    Post the code you're asking about **in the question itself**, as text. Not as a link to an image. We can't copy and paste from an image. Blind people can't read an image. – JB Nizet Aug 10 '18 at 15:58
  • Polymorphism. And because `Top` is not abstract. – Andrew Li Aug 10 '18 at 15:58
  • 1
    Why should `Top` know that a subclass provides a default constructor? – Lino Aug 10 '18 at 15:58
  • Also there exists no such thing as [constructor-inheritance](https://stackoverflow.com/questions/1644317/java-constructor-inheritance) in the first place – Lino Aug 10 '18 at 15:59

2 Answers2

0

I'm confused as to why Top t = new Top()

Because Top has no no-args constructor. If you add one like you did in Bottom it will become valid.

Antoniossss
  • 31,590
  • 6
  • 57
  • 99
0

When you initialized the constructor Top(int top), you put an int as a parameter, so you have to pass an int when you call the constructor. It works just like you are using a normal method. The argument type must match the parameter type. You can't pass void argument to a method initialized with an int, or double parameter.

zin
  • 112
  • 8