0

I recently learnt about inheritance and noticed that if all the subclasses inherited the public/protected methods from its superclasses, does that mean we have multiple copies of the same method? Isn't that a waste of space?

Eg:

class Shape
{
 //some code
 public void rotateShape()
 {...}
 //some code
}

class Triangle extends Shape
{
}

class Square extends Shape
{
}

So does this mean I have 3 copies of the method rotateShape() belonging to the 2 subclasses and 1 superclass assuming I instantiate an object from each class?

HelloWorld
  • 193
  • 2
  • 8
  • No, the base class isn't compiled separately unless instantiated as well. – Adrian M. Jul 05 '20 at 02:59
  • Are you saying that if it was compiled, we would get 3 copies of the `rotateShape()` method? – HelloWorld Jul 05 '20 at 03:02
  • [Learning the Java Language](https://docs.oracle.com/javase/tutorial/java/TOC.html) – Abra Jul 05 '20 at 03:03
  • The subclasses _don't_ have copies, as you can see right in here in the code. (If you want to get technical, this is why there's a difference between [`invokevirtual`](https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-6.html#jvms-6.5.invokevirtual) and the other `invoke*` instructions.) – chrylis -cautiouslyoptimistic- Jul 05 '20 at 03:04

2 Answers2

2

The JVM specification page 570 implies that the answer to your question is "no"; a virtual method that is not overriden will use the superclass's version of that method directly, rather than make a copy of it for its own use.

See this previous answer for more info on vtable dispatch.

Putnam
  • 704
  • 4
  • 14
0

As i understand your question, you are trying to ask if we instantiate object from each class so this is the waste of space? mean one object from Shape, one from Triangle and one from Square. When a inheritance is used in any class than base class and derived class combine together and make single copy. This is the beauty of object oriented that you don't need to write your Rotate Shape function again you are just getting it from base class.

Danish Ahmed
  • 490
  • 5
  • 6