如何使用另一个类的变量值?

时间:2016-09-13 20:51:02

标签: java

如何在detailgrouping类中获取firstname变量作为name类中firstname的输入? 感谢您提出任何建议并尝试理解。

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);
    }
}

2 个答案:

答案 0 :(得分:0)

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);
} }

这将有效

答案 1 :(得分:0)

好像你的详细分组'课程想要访问您的姓名'上课,'缅因州'是使用这两个类的启动器。 如果要访问存储用户输入值的变量,您可能应该创建类' Name'的成员变量。以及它的getter / setter。你的代码应抛出编译时错误atm,说明" firstname'变量未在类' DetailGrouping'中声明。您可能还想检查方法执行的范围/边界。您的变量不存在于声明它们的方法之外。

工作代码是:

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);

    }
}