Results 1 to 13 of 13

Thread: Instanceof

  1. #1
    KevinNguyen is offline Member
    Join Date
    Oct 2012
    Posts
    18
    Rep Power
    0

    Default Instanceof

    Hi guys, for example, I have class A, B extends A. I create an ArrayList<A> to contain both A and B

    Java Code:
    ArrayList<A> lst = new ArrayList<A>();
    lst.add(new B(args));
    So when I check if an object is instance of B

    Java Code:
    if (lst.get(0) instanceof B) {
    //Do something
    }
    else if (lst.get(0) instanceof A) {
    //Do something 
    }
    two conditions will be true. I wanna ask if there is any way to recognise that lst.get(0) is only an instance of B so the second condition should not be done.
    Thanks.
    Last edited by KevinNguyen; 11-08-2012 at 03:44 PM.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,876
    Rep Power
    8

    Default Re: Instanceof

    You're using an else if. If the first condition is true, the second condition will never even be evaluated.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    KevinNguyen is offline Member
    Join Date
    Oct 2012
    Posts
    18
    Rep Power
    0

    Default Re: Instanceof

    Oh, sorry. In my case
    Java Code:
    for (int j = 0; j < lst.size(); j++) 
                        	if (lst.get(j) instanceof B) {
                        		System.out.println(lst.get(j));
                        	}
    Java Code:
    for (int j = 0; j < lst.size(); j++) 
                        	if (lst.get(j) instanceof A) {
                        		System.out.println(lst.get(j));
                        	}
    the second code block will also print the first result.

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,876
    Rep Power
    8

    Default Re: Instanceof

    So why don't you just do the checks together, like in your first example? Or use a compound boolean expression (using && or ||).
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    KevinNguyen is offline Member
    Join Date
    Oct 2012
    Posts
    18
    Rep Power
    0

    Default Re: Instanceof

    Yo, I use switch() to select what to do so I have to split them. I will also post source here:
    Java Code:
    package QuestionDatabaseManagement;
    
    import java.io.*;
    import java.util.*;
     
    public class Question {
    	protected String ques, ans;	
    	protected int type; //0:NOTSET(only use to initial beginning value)
        //1:MATH | 2.PHYSICS | 3.ENG | 4.LITERATURES | 5.CHE | 6. ASTRO
        //7. GEO | 8. BIO | 9: HIS | 10: LAW | 11: ARTS&CULTURE
        //12.UNDEFINED
    	protected String[] Category = {"NOTSET","MATH","PHY","ENG",
                   "LIT","CHE","ASTRO","GEO","BIO","HIS","LAW","ARTS & CULTURE","UNDEFINED"};
    	
    	protected int dif; 	//0: NOTSET
    						//1: EASY | 2: MEDIUM | 3: HARD
    						//4: UNDIFINED
    	protected String[] Dif = {"NOTSET","EASY","MEDIUM","HARD","UNDEFINED"};
    	
    	public String getQues() {
    		return ques;
    	}
    
    	public void setQues(String ques) {
    		this.ques = ques;
    	}
    
    	public String getAns() {
    		return ans;
    	}
    
    	public void setAns(String ans) {
    		this.ans = ans;
    	}
    
    	public int getType() {
    		return type;
    	}
    
    	public void setType(int type) {
    		this.type = type;
    	}
    
    	public int getDif() {
    		return dif;
    	}
    
    	public void setDif(int dif) {
    		this.dif = dif;
    	}
    	
    	public Question(String ques, String ans, int type, int dif) {
    		this.ques = ques;
    		this.ans = ans;
    		this.type = type;
    		this.dif = dif;
        }
     
        public Question() {
            this("","",0,0);
        }
        
        public String toString() {
            return 	"Type: " + type +
            		"\nDificulty: " + dif +
            		"\nQuestion: " + ques +
            		"\nAnswer: " + ans +
            		"\n***************************************************************************************";
        }
        
        public void input() {
        	System.out.print("Enter type: ");
     	    type = new Scanner(System.in).nextInt();
     	    System.out.print("Enter difficulty: ");
     	    dif = new Scanner(System.in).nextInt();
     	    System.out.print("Enter question: ");
     	    ques = new Scanner(System.in).nextLine();  
     	    System.out.print("Enter answer: ");
    	    ans = new Scanner(System.in).nextLine();
        }
        
    }
    Java Code:
    package QuestionDatabaseManagement;
    
    import java.io.*;
    import java.util.*;
     
    public class MultiChoiceQuestion extends Question implements Serializable {
    
    	private static final long serialVersionUID = 7189152575673931024L;
    	
    	private String optA, optB, optC, optD;
    	private static int count = 0;
    	
    	public int getCount() {
    		return count;
    	}
    	
        public String getOptA() {
            return optA;
        }
     
        public void setOptA(String optA) {
            if (optA.length()>0) 
                this.optA = optA;
        }
     
        public String getOptB() {
            return optB;
        }
     
        public void setOptB(String optB) {
            if (optB.length()>0)
                this.optB = optB;
        }
     
        public String getOptC() {
            return optC;
        }
     
        public void setOptC(String optC) {
            if (optC.length()>0)
                this.optC = optC;
        }
     
        public String getOptD() {
            return optD;
        }
     
        public void setOptD(String optD) {
            if (optD.length()>0)
                this.optD = optD;
        }
    
        public MultiChoiceQuestion(String ques,
    			String optA, String optB, String optC, String optD, String ans, int type, int dif) {
        	super(ques,ans,type,dif);
    		this.optA = optA;
    		this.optB = optB;
    		this.optC = optC;
    		this.optD = optD;
    		count++;
    	}
    
    	public MultiChoiceQuestion() {
            this("","","","","","",0,0);
        }
    
    	 public void input() {
    	    System.out.print("Enter type: ");
    	    type = new Scanner(System.in).nextInt();
    	    System.out.print("Enter difficulty: ");
    	    dif = new Scanner(System.in).nextInt();
    	    System.out.print("Enter question: ");
    	    ques = new Scanner(System.in).nextLine();
    	    System.out.print("Enter option A: ");
    	    optA = new Scanner(System.in).nextLine();
    	    System.out.print("Enter option B: ");
    	    optB = new Scanner(System.in).nextLine();
    	    System.out.print("Enter option C: ");
    	    optC = new Scanner(System.in).nextLine();
    	    System.out.print("Enter option D: ");
    	    optD = new Scanner(System.in).nextLine();
    	    System.out.print("Enter answer: ");
    	    ans = new Scanner(System.in).nextLine();
    	}
    
        public String toString() {
            return "Type: " + Category[type] +
            "\nDifficulty: " + Dif[dif] +
            "\nQuestion: " + ques +
            "\n\tA. " + optA +
            "\n\tB. " + optB +
            "\n\tC. " + optC +
            "\n\tD. " + optD +
            "\nAnswer: " + ans +
        	"\n***************************************************************************************";
        }
        
    }
    Java Code:
    package QuestionDatabaseManagement;
     
    import java.util.*;
    import java.io.*;
      
    public class QuestionManagement {
    	public static void main(String[] args) throws NoSuchElementException, IOException, ClassNotFoundException {
        	ArrayList<Question> Data = new ArrayList<Question>();
        	
        	FileOutputStream file_out = new FileOutputStream("data.dat");
        	Data.add(new MultiChoiceQuestion("Bộ phim hoạt h́nh nổi tiếng Shrek của hăng nào sản xuất?","Walt Disney","Pixar","DreamWorks Animation","Madhouse","C",11,2));
        	Data.add(new MultiChoiceQuestion("Số tiếp tục trong dăy số dưới đây là số nào?: 6 20 62 188","564","566","568","600","B",1,1));
        	Data.add(new MultiChoiceQuestion("Nước ở đâu rộng nhất Thế Giới ?","Mỹ","Nga","Trung Quốc","Khác","D",7,1));
        	Data.add(new MultiChoiceQuestion("Bạn có biết có khoảng bao nhiêu ngôn ngữ có trên trái đất?","3500","4700","6500","7300","C",11,2));
        	Data.add(new MultiChoiceQuestion("Trong 4 con vật sau đây, th́ con nào có đặc điểm ít giống nhất với 3 con c̣n lại?","Chó","Voi","Mèo","Rùa","D",8,1));
        	Data.add(new Question("Sông nào có một bởi ở châu Âu, một bởi ở châu Á??","Sông U-ran",7,2));
        	Data.add(new Question("Hành tinh nào lớn nhất trong hệ Mặt Trời?","Mộc tinh",6,1));
        	Data.add(new Question("Trong bức tranh đám cưới chuột có tất cả bao nhiêu con chuột?","12",3,3));
        	Data.add(new Question("Đồng bằng nào lớn nhất thế giới?","Amazon",4,4));
        	Data.add(new Question("Chữ cái cuối cùng trong bảng chữ cái Hy Lạp?","Omega",5,0));
        	ObjectOutputStream StreamOut_1 = new ObjectOutputStream(file_out);
        	StreamOut_1.writeObject(Data);
     		StreamOut_1.close();
     		
        	FileInputStream file_in = new FileInputStream("data.dat");
        	ObjectInputStream StreamIn = new ObjectInputStream(file_in);
        	Data = (ArrayList)StreamIn.readObject();
        	StreamIn.close();
        	
            Scanner Sc = new Scanner(System.in);
            boolean isReturnable = true;
            int index;
    	        
            while (isReturnable == true) {
            	int s;
                //System.out.println("***************************************************************************************");
            	System.out.println("Please select one: ");
                System.out.println("\t1. Add a multiple choice question");
                System.out.println("\t2. Add a question");
                System.out.println("\t3. Delete a multiple choice question");
                System.out.println("\t4. Delete a question");
                System.out.println("\t5. Edit a multiple choice question");
                System.out.println("\t6. Edit a question");
                System.out.println("\t7. Report: Multiple choice question database");
                System.out.println("\t8. Report: Question database");
                System.out.println("\t9. Report: All database");
                System.out.println("\t10. Save");
                System.out.println("\t11. Exit");
    		    System.out.printf("Enter your choice: ");
    		    s = Sc.nextInt();
                System.out.println("***************************************************************************************");
                
                switch (s) {
                    case 1:
                        MultiChoiceQuestion MQue = new MultiChoiceQuestion();
                        MQue.input();
                        Data.add(MQue);
                        Sc.nextLine();
                        isReturnable = true;
                        break;
                        
                    case 2:
                    	Question Que = new Question();
                    	Que.input();
                    	Data.add(Que);
                    	Sc.nextLine();
                        isReturnable = true;
                        break;
                        
                    case 3:
                    	System.out.print("Please enter index number of the question, 0 to go back to menu " +
                    			"you want to delete (if you don't know please consider use option 9 to see): " );
                    	index = Sc.nextInt();
                    	if (index == 0) break;
                    	else
                    		if ((index-1)<Data.size() && Data.get(index-1) instanceof MultiChoiceQuestion) {
                    			Data.remove(index-1);
                    			System.out.println("Entry deleted.");
                    		}
                    		else System.out.println("Cannot delete entry due to wrong type of question. Operation aborted.");
                    	isReturnable = true;
                        break;
                        
                    case 4:
                    	System.out.print("Please enter index number of the question, 0 to go back to menu " +
                    			"you want to delete (if you don't know please consider use option 9 to see): " );
                    	index = Sc.nextInt();
                    	if (index == 0) break;
                    	else
                    		if ((index-1)<Data.size() && Data.get(index-1) instanceof Question) {
                    			Data.remove(index-1);
                    			System.out.println("Entry deleted.");
                    		}
                    		else System.out.println("Cannot delete entry due to wrong type of question. Operation aborted.");
                    	isReturnable = true;
                        break;
                        
                    case 5:
                    	System.out.print("Please enter index number of the question, 0 to go back to menu " +
                    			"you want to edit (if you don't know please consider use option 7 to 9 to see): " );
                    	index = Sc.nextInt();
                    	if (index == 0) break;
                    	else
                    		if ((index-1)<Data.size() && Data.get(index - 1) instanceof MultiChoiceQuestion) {
                    			MultiChoiceQuestion temp = new MultiChoiceQuestion();
                    			temp.input();
                    			Data.set(index - 1, temp);
                    			System.out.println("Entry edited.");
                    		}
                    		else System.out.println("Cannot edit entry due to wrong type of question. Operation aborted.");
                    	isReturnable = true;
                        break;
    
                    case 6:
                    	System.out.print("Please enter index number of the question, 0 to go back to menu " +
                    			"you want to edit (if you don't know please consider use option 7 to 9 to see): " );
                    	index = Sc.nextInt();
                    	if (index == 0) break;
                    	else
                    		if ((index-1)<Data.size() && Data.get(index - 1) instanceof Question) {
                    			Question temp = new Question();
                    			temp.input();
                    			Data.set(index - 1, temp);
                    			System.out.println("Entry edited.");
                    		}
                    		else System.out.println("Cannot edit entry due to wrong type of question. Operation aborted.");
                    	isReturnable = true;
                        break;
                        
                    case 7:
                        for (int j = 0; j < Data.size(); j++) 
                        	if (Data.get(j) instanceof MultiChoiceQuestion) {
                        		System.out.println("Question index: " +(j+1));
                        		System.out.println(Data.get(j));
                        	}
                        isReturnable = true;
                        break;
                        
                    case 8:
                        for (int j = 0; j < Data.size(); j++) 
                        	if (Data.get(j) instanceof Question) {
                        		System.out.println("Question index: " +(j+1));
                        		System.out.println(Data.get(j));
                        	}
                        isReturnable = true;
                        break;
                        
                    case 9: 
                    	for (int j = 0; j < Data.size(); j++) {
                    		System.out.println("Question index: " +(j+1));
                    		System.out.println(Data.get(j));
                    	}
                    	isReturnable = true;
                        break;
                    
                    case 10: 
                    	ObjectOutputStream StreamOut_2 = new ObjectOutputStream(new FileOutputStream("data.dat"));
                    	StreamOut_2.writeObject(Data);
                 		StreamOut_2.close();
                    default: break;
                }  
            }
        } 
    }
    After add new MultiChoiceQuestion I select option 8 to display Question only but it will also display the MultiChoiceQuestion that I just added. So that I mean if there is some way to let it only display Question instead of display the MultiChoiceQuestion also cause I know that ́ B extends A so instanceof B will also an instanceof A.
    Last edited by KevinNguyen; 11-08-2012 at 03:53 PM.

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,876
    Rep Power
    8

    Default Re: Instanceof

    Quote Originally Posted by KevinNguyen View Post
    Yo, I use switch() to select what to do so I have to split them. I will also post source here:
    I'm not sure how that changes my advice?

    Although one might wonder why you have to call instanceof so many times. Usually that's a sign that some refactoring is in order.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    KevinNguyen is offline Member
    Join Date
    Oct 2012
    Posts
    18
    Rep Power
    0

    Default Re: Instanceof

    My problem is if I want to display Question's object it will also display MultiChoiceQuestion. I want to make it display only Question's objects :)

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,830
    Rep Power
    19

    Default Re: Instanceof

    But that implies your model is wrong, since you have said (by your code) that a MultiChoiceQuestion is-a Question.
    If they are not, then they should not be extending Question.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    KevinNguyen is offline Member
    Join Date
    Oct 2012
    Posts
    18
    Rep Power
    0

    Default Re: Instanceof

    Ya sure that, but MultiChoiceQuestion is-a Question.
    My java assignment topic is to create a program to manage question for a gameshow. So there will be MultiChoiceQuestion and Question(don't know if I use wrong word, you know Question - Answer not Question - A, B, C, D) so if I create a parent class, it will also the SAME as Question class ( String ques, String ans, int type and int difficulty). That's why I create MultiChoiceQuestion extends Question. Sure that my solution is not good and maybe wrong. That's why I need everybody helps :D

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,830
    Rep Power
    19

    Default Re: Instanceof

    But in your app it clearly isn't the case, because otherwise you wouldn't have to somehow split them up.
    Your own logic is showing that this is not the correct relationship.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    KevinNguyen is offline Member
    Join Date
    Oct 2012
    Posts
    18
    Rep Power
    0

    Default Re: Instanceof

    Sure, so the problem is I can't find the way to design the parent class for MultiChoiceQuestion and Question cause if I create it, it will be the same as Question. You have any idea?

  12. #12
    KevinWorkman's Avatar
    KevinWorkman is online now Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,876
    Rep Power
    8

    Default Re: Instanceof

    Perhaps instead of having all these different kinds of questions, have a single Question Object with several boolean attributes: isMultipleChoice, isTrueFalse, etc. Then just check them instead of using the instanceof keyword.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,830
    Rep Power
    19

    Default Re: Instanceof

    I'd have them as two separate classes, in two arrays.
    One Multi, one "normal".

    They would each implement a AskQuestion interface (or some better name).
    That would have an askQuestion method and a checkAnswer (or something) method.

    I say this, since you seem to be treating a MultiQuestion and a Question as two very different things (looking at the options).
    It's only when you actually ask the question that they do similar things (and there's no code for that at the moment).
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 24
    Last Post: 03-12-2012, 06:28 PM
  2. instanceof
    By AedonetLIRA in forum New To Java
    Replies: 3
    Last Post: 12-01-2010, 12:34 AM
  3. Class, SubClass type (InstanceOf) Question
    By indyjoel in forum New To Java
    Replies: 6
    Last Post: 11-07-2010, 03:55 AM
  4. Use of keyword instanceof
    By darek9576 in forum New To Java
    Replies: 3
    Last Post: 03-14-2010, 10:35 PM
  5. super instanceof Class?
    By mikeiz404 in forum New To Java
    Replies: 11
    Last Post: 01-23-2009, 07:23 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •