Results 1 to 3 of 3
  1. #1
    jonathan.vaz is offline Member
    Join Date
    Sep 2013
    Posts
    5
    Rep Power
    0

    Default Accessing an instance of an object from another method

    Hi guys,

    Can someone please let me know how to access an instance of an object within another method from another method.

    Thanks in Advance

    Java Code:
    package javatuts;
    
    import java.util.Scanner;
    
    public class generic_func {
    
    void User_Input(){
    	Scanner scan = new Scanner(System.in);
    	scan.next();
    
    			
     
    			}
    
    void input_val(){
    	
    	// I want to use the scanner instance i.e scan here.
    	
    	
    }
    
    }

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,652
    Blog Entries
    7
    Rep Power
    21

    Default Re: Accessing an instance of an object from another method

    Variable 'scan' is a local variable so invisible to other methods, unless you explicitly pass it to the other method(s) as a parameter; as in:

    Java Code:
    void User_Input() {
       Scanner scan = new Scanner(System.in);
       ...
       input_val(scan); // pass local variable 'scan'
    }
    
    void intput_val(Scanner scan) {
       // use parameter 'scan' here
    }
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    jonathan.vaz is offline Member
    Join Date
    Sep 2013
    Posts
    5
    Rep Power
    0

    Default Re: Accessing an instance of an object from another method

    Thanks a lottt Jos. was of great help.

Similar Threads

  1. Accessing an object from within another object from the same type in Java
    By mhasgari in forum Threads and Synchronization
    Replies: 5
    Last Post: 06-20-2011, 04:21 PM
  2. object and instance
    By anurag in forum New To Java
    Replies: 1
    Last Post: 05-14-2010, 08:51 PM
  3. Accessing instance outside of creation method
    By meringue in forum New To Java
    Replies: 6
    Last Post: 03-22-2009, 01:36 AM
  4. accessing instance variables from static methods
    By ravian in forum New To Java
    Replies: 7
    Last Post: 03-01-2009, 10:09 PM
  5. [SOLVED] Non-synchronized instance method of an Object
    By piyu.sha in forum Threads and Synchronization
    Replies: 2
    Last Post: 10-06-2008, 06:35 AM

Posting Permissions

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