Valid object declarations and using dot operators

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Valid object declarations and using dot operators


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.





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 at 15:58





Polymorphism. And because Top is not abstract.
– Li357
Aug 10 at 15:58


Top





Why should Top know that a subclass provides a default constructor?
– Lino
Aug 10 at 15:58


Top





Also there exists no such thing as constructor-inheritance in the first place
– Lino
Aug 10 at 15:59




2 Answers
2



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.


Top


Bottom



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.


Top(int top)


void


int


double






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS