简体   繁体   中英

How to use a variable value from another class?

How do i get firstname variable in the detailgrouping class to be the input from firstname in the name class? Thank you for any advice and just trying to understand.

class maine {
    public static void main (String args []){       
        name nameObject = new name ();
        detailgrouping detailObject = new detailgrouping(); 

        nameObject.usernames ();
        detailObject.collect ();

     }
}
import java.util.Scanner
public class name {
    public void usernames (){
        Scanner scnkey =new Scanner (System.in);    
        System.out.println("Users first name"); 
        String firstname = scnkey.nextLine();   
        System.out.println("Users last name");  
        String lastname = scnkey.nextLine();
    }
}

public class detailgrouping {
    public void collect (){ 
        System.out.println(" Users first name: " + firstname);
    }
}
public class name { String firstname; public void usernames (){ Scanner scnkey =new Scanner (System.in); System.out.println("Users first name"); firstname = scnkey.nextLine(); System.out.println("Users last name"); String lastname = scnkey.nextLine(); } } public class detailgrouping extends name { public void collect (){ System.out.println(" Users first name: " + firstname); } }

This will work

Seems like your 'DetailGrouping' class wants to access your 'Name' class, and 'Maine' is the launcher using both these classes. If you want to access vars in which you are storing user input values, you probably should create member variables of class 'Name' along with its getter/setter. Your code should throw compile time error atm, stating 'firstname' variable is not declared in class 'DetailGrouping'. You may also want to check the scope/boundaries of method execution. Your vars dont exist outside of the method that they are declared in.

The working code is :

Package myPackage;
import java.util.Scanner;


class name {
    String firstname, lastname;
    public void usernames (){
        Scanner scnkey =new Scanner (System.in);
        System.out.println("Users first name");
        firstname = scnkey.nextLine();
        System.out.println("Users last name");
        lastname = scnkey.nextLine();
    }
}

class detailgrouping {
    public void collect (name obj){
        System.out.println(" Users first name: " + obj.firstname);
    }
}

class maine{
    public static void main (String args []){
        name nameObject = new name ();
        detailgrouping detailObject = new detailgrouping();

        nameObject.usernames ();
        detailObject.collect (nameObject);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM