سؤال

I have an abstract class and a class which extends it and implements the methods without adding further methods of its own. Let's call the classes A and B. B extends A. should i create an instance of class B like this

A newInstance = new B();

or like this

B newInstance = new B();

Does it make any difference and which is a better practice ?

هل كانت مفيدة؟

المحلول

Does it make any difference and which is a better practice ?

Programming to an interface rather to an implementation it's the preffered way, Read more here --> What does it mean to "program to an interface"? . The difference is that you follow a contract rather than an implementation if you have to change the implementation with the same contract you ensure that you only have to change the object creation part.

In your example if you define like this

A newInstance = new B();

You only can use methods that are visible in A contract.

And in this case:

B newInstance = new B();

You can use methods that are visible in B contract, and as B has a IS-A relationship with A you can use A methods too.

نصائح أخرى

For maintainability, I'd go for the second one:

B newInstance = new B();

Obviously, it doesn't matter currently, since A and B are identical in terms of fields and methods (according to what you said).

However, say your class B changes. You add a method, or a field. If you declared your new instance as A newInstance = new B(), you cannot access the change you made in B.

And just as a second point, it makes more sense from a layman's perspective, to use the second one.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top