What is wrong with my java codes?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • phpuser123
    New Member
    • Dec 2009
    • 108

    What is wrong with my java codes?

    I just happened to read abt vectors in java..For some practice,I implemented this small script where I Store objects in a vector..Then,I want to invoke the methods of the corresponding objects.My problem is that in this line

    System.out.prin tln(vc.elementA t(i).test3());

    the test3() method of my object is being underlined..I know I am retrieving an abject from vc.elementAt(i) ,then why is the method test3() being underlined??


    Code:
    import java.util.*;
    public class MITlab2 {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		 test_vector1();
    	}
    	
    	
    	public static void test_vector1(){
    		test_class vm=new test_class();
    		Vector vc=new Vector();
    		vc.add(vm);vc.add(vm);vc.add(vm);
    		System.out.println(vc.size());
    		for (int i=0;i<vc.size();i++){
    			System.out.println(vc.elementAt(i).test3());
    		}
    		
    	}
    
    }
    class test_class{
    	public String vim="testing";
    	public boolean test3(){
    		return true;
    	}
    }
  • Dheeraj Joshi
    Recognized Expert Top Contributor
    • Jul 2009
    • 1129

    #2
    You code in line 19 should be changed.

    Code:
    ((test_class) vc.elementAt(i)).test3()
    This is because test3 function is the member of test_class and you are using it in MITLab2 class.

    Regards
    Dheeraj Joshi

    Comment

    • konapalligopi
      New Member
      • May 2010
      • 2

      #3
      return type is object

      There The return type is Object so u need to do implicit conversion buddy

      Comment

      • phpuser123
        New Member
        • Dec 2009
        • 108

        #4
        Thanks dheerajjoshim and konapalligopi,T he code worked...
        But I hava a slight problem understanding this...

        I used vm.test3() and it worked fine but then why didn't it work on vc.elementAt(i) .test3()??

        Why does it work with vm.test3() when vm also is an object....Why i don't have to do this conversion??A bit confused here...

        Comment

        • jkmyoung
          Recognized Expert Top Contributor
          • Mar 2006
          • 2057

          #5
          You've explicitly declared vm as a test_class object.
          vc.elementAt(i) is just an object, needs to be explicitly cast.

          You could always set your vector to only hold test_class objects (assuming you're using java 1.5 or higher.

          eg Vector <test_class> vc=new Vector<test_cla ss>();

          Comment

          Working...