class - Confusion about extended classes in Java -
i having confusion extended classes. think best way explain want skeleton code:
abstract class player { public int solve() { // 1 method of solving problem } } class otherplayer extends player { public char solve(int num) { //different method of solving same problem } } // suspect wrong way create player player first = new otherplayer; // because gives me error... first.solve(5)' // , uses super class's method of solving problem first.solve(); // don't want though... otherplayer first = new otherplayer; // because define players in method // returns type player(): private player genplayer() { // take input keyboard player newplayer; if (specific set of answers) newplayer = new otherplayer(); else newplayer = new player(); homecoming newplayer; }
my understanding of extended classes limited. if "typea var = new typeb", , typeb extends typea, seems var has access methods in typea class. do, new typeb? why legal way instantiate variable? , how recommend restructure programme can create work (i'd prefer maintain method, don't have create mess every time create player)?
i want know how create extended class if person knew doing.
you need like:
abstract class player { abstract void solve(int num); } class otherplayer extends player { void solve(int num) { //... } }
that is, phone call method through variables of type player
, @ to the lowest degree signature must declared on class - , must implemented in subclasses. there no way phone call method may or may not exist in subclass using variable of superclass type.
imagine this:
class player { // ... } class fooplayer extends player { void solveint(int num) { // ... } } class barplayer extend player { void solvestring(string s) { // ... } } player[] players = new[] {new fooplayer(), new barplayer()}; // sort of code want work (player p : players) { p.solveint(123); }
what's supposed happen when method called on barplayer
? can see, doesn't create much sense allow this.
while it's not useful player player = new fooplayer()
explicitly, allow not have know exact subtype of player
value is. it's missing point @ methods different between subtypes - point of polymorphism same method (i.e. same signature) implemented in different way between subclasses:
class player { abstract string greet(); } class englishplayer extends player { string greet() { homecoming "hello"; } } class japaneseplayer extends player { string greet() { homecoming "konnichi wa"; } }
java class abstract extends
No comments:
Post a Comment