java - How to know if a particular object belongs to a class? -


i have following classes in program:

public abstract class question {      private topic topic;     private string text;      // methods  }  public class openquestion extends question {      // methods  }  public class multiplechoicequestion extends question {      private list<string> options = new arraylist<string>();     private string correct;      // methods  } 

also, there class test have:

question question;  // if question open      if(question instanceof openquestion) {      ...      }  // if question multiple choice      if(question instanceof multiplechoicequestion) {      ...      } 

i'm trying find alternative instanceof, because i've been told breaks oop principle.

is there other better way know if question open or multiple choice?

the instanceof keyword not break oop principle. meant should use polymorphism execute logic.

instead of:

if(question instanceof openquestion) {  ... }  //countless ifs  if(question instanceof multiplechoicequestion) { ...  } 

you should

question.doaction(); 

another example (more explicit):

abstract class animal{     public abstract void speak(); }  class dog extends animal{     public void speak(){ system.out.println("bark!"); } }  class cat extends animal{     public void speak(){ system.out.println("meow!"); } } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -