It’s been a while since I did anything with Java OOP, so I’m a bit rusty and wanted some clarification.
In Java, if I remember correctly, one could declare a superclass and instantiate a subclass; for example, Superclass myObject = new Subclass().
One could then pass myObject into a function that accepted a Superclass parameter, and access any Superclass properties/methods using the reference.
Here’s where things get foggy – if you want to access Subclass-specific methods/variables, can you do that directly with myObject (which was declared as a Superclass) or do you need to cast it first to a Subclass type?
If we roll this over to C# now, does the same logic apply? I’m running into some weird issues trying to duplicate this behavior. The specific use case I’m looking at is:
//These are just declarations for ease-of-reading
Superclass bar = new Subclass();
public static void doSomething(Superclass foo) {...}
//Logic
doSomething(bar);
bar.superOnly() //Should this work?
bar.subOnly() //Should this work?
bar.subOverrided() //Will this call the superclass or subclass version?
I’m looking up this stuff in tutorials as well, but most examples seem to be simple “Subclass myObject = new Subclass()” instances with trivial output. Nothing I’ve found so far covers the nebulous world of function parameters.
If anyone can help me out, or point me to a specific resource that covers function parameters and OO in C#, I would greatly appreciate it!
Yes, that’s what polymorphism is for. Virtual methods of the base class that are overridden in the derived class will always be called, even if you call the method through a reference of the base type.
Yes, the principle is the same
As for your example:
Yes
No, because the compiler wouldn’t know about this method
Yes, thanks to polymorphism