Student level question, I'm hoping stackOverflow can help me gain a deeper understanding here:
I've noticed that many of the methods (such as those in Graphics2D, for example) in the Java API have "abstract" modifiers. Why is this?
I'm just wrapping my head around inheritance and polymorphism right now, but as I understand it, an abstract class is meant to be used as a kind of "parent class" that is extended by sub-classes, and that abstract classes themselves cannot be instantiated.
I also understand that abstract methods are declared (but not implemented) in an abstract class, and supposedly must be implemented within a subclass for that subclass to be considered non-abstract (and to therefore be instantiable).
So, how is it that I'm able to import a class like Graphics2D, create an instance of it and use its abstract methods?
My instructor mentioned something about the methods being overwritten at run-time (?), but I don't understand how/why. Obviously I'm missing something here, I'd love more insight!
So, how is it that I'm able to import a class like Graphics2D, create an instance of it and use its abstract methods?
Because you never create an instance of Graphics2D
directly. Look at your code - you won't find this:
Graphics2D graphics = new Graphics2D(); // This wouldn't compile
... anywhere. Instead, you'll find calls to methods that return a Graphics2D
, which are actually returning references to instances of concrete subclasses. Or maybe you'll provide methods which accept a Graphics
or a Graphics2D
parameter which the caller provides... and the caller may know about the concrete class, or they may have obtained a reference from elsewhere too.
In some ways, that's the whole point - the fact that you're even wondering where these subclasses are is proof about how well the whole thing is working... you only ever need to deal with Graphics2D
, but the implementation details of that can differ by platform etc.
When your instructor was talking about methods being overwritten, I suspect they actually said overridden - where a subclass can provide a more specific implementation of a method than a superclass, or indeed may provide one where the superclass only has the abstract method declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With