❔ Question about data types and classes

object cube1 = new Cube(7); what exactly happens here when i have a different variable type but I still set it equal to a new (whatever the class is) with the class being different than the data type. - so here I have the data type object but setting it equal to new Cube. how does it work when u do something like this. does the variable still use the methods and properties in cube because it is set as new cube or not because the datatype is object?
2 Replies
FusedQyou
FusedQyou2y ago
Every type inherits from object, so as long as the implementing type (in this case Cube) supports the variable type (in this case object), the compiler won't complain. The only problem with this is that the variable only supports methods, fields and properties up to the variable type (object). So in this case, none of the Cube methods can be used unless you apply casting. Only the methods from object are supported. You also have a dynamic type that allows you to call any variable, field and property you can think off, but it's very prone to errors due to the lack of syntax. I strongly recommend against it. If you want your variable to support your methods or properties (not fields in this case), you should define an interface that implements these. Your Cube would then use this interface. Lastly, you can make your cube inherit from a base type (like Shapes), and this would define general methods that apply to all types that inherit from it. You can even combine it with interfaces. Maybe google "inheritance", "polymorphism", "abstraction" and "interface" for more info.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server