java - Liskov Substitution Principle and casting -


this question has answer here:

i have come across liskov substitution principle , casting during lecture of (java) object-oriented programming. understand principle states, is, can initialise subclass type of superclass:

superclass superclass = new subclass(); 

my first concern regards purpose of such operation. why can't declare subclass usual (example follows)?

subclass subclass = new subclass(); 

right after this, got stuck on casting, follows:

superclass superclass = new subclass(); subclass subclass = (subclass)superclass; 

again, struggle understanding point of of this.

can provide clarification on purpose of these procedures?

liskov substitution principle means subclasses should done understanding should really care subclass instance when gets instantiated. onwards, should treated superclass no added methods or special treatment.

the biggest advantage approach should decide want replace 1 subclass another, could! called in precisely same way previous subclass called. if isn't convenient new subclass, liskov means shouldn't subclass of superclass. subclasses should treated indiscriminately.

regarding casting, when assign subclass superclass, have instance can use throughout entire program without caring subclass specifically. following line try cast superclass instance subclass can done, you're probably not doing correctly (again, because shouldn't care subclass is).

generally you'll see factory or method instantiate follows:

public superclass getsuperclass() {     subclass subclass = new subclass();      // here place should perform subclass specific     // calls.  less need here, better.     subclass.setsubclassproperty(this);      return subclass; } 

note implicit cast superclass return subclass instance , caller given superclass instance. how prefer it. caller receive subclass instance instead, wouldn't want temptation caller use subclass methods.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -