2014-09-29 58 views
1

所以我是一个新手学习'回合类和面向对象在java中。移动设备的每个实例都会保存模型,所有者名称和编号。所以在主文件中,我尝试使用这些参数和一个标识符来创建一个新实例的方法。但是,编译表示mobName已经在createMobile中定义。它应该是一个可以指向使用“mob1”的实例。任何帮助?如何使用在Java中创建实例的参数创建方法?

class PhoneSystem{ 

    public static void main(String[] args){ 

      createMobile("mob1", "Android S4", "John Doe", 13374042); 
     } 

     public static void createMobile(String mobName, String brand, String owner, int number){ 
      Mobile mobName = new Mobile(); 
      mobName.SetBrand(brand); 
      mobName.SetOwner(owner); 
      mobName.SetNumber(number); 
     } 
} 

回答

4
public static void createMobile(String mobName, String brand, String owner, int number){ 
     Mobile mobName = new Mobile(); 
    ... 

这两行是你的问题所在。你已经定义了一个String mobName。之后,您尝试定义一个与Mobile mobName同名的变量。即使在方法声明和方法中,变量也不能共享相同的名称。有一个独特的案例,这是可能的,但涉及领域和实例,超出了这个问题的范围。

既然你想mob1你应该做的:

 Mobile mob1 = new Mobile(); 

此外,您还没有指定,如果你想mob1是它的名称或变量名。如果你想让设备被称为mob1,你应该做到这一点,所以Mobile将设备名称作为字符串。还有另一种方法可以通过MapMobile实例与名称关联起来,但由于您在说您正在学习面向对象,这可能也不在范围之内,因为它涉及Collection

但是,您提供的当前代码会导致mob1在方法结束时超出范围。也许你想return它到主类?

public static Mobile createMobile(String mobName, String brand, String owner, int number){ 
     Mobile mob1 = new Mobile(); 
    ... 
     return mob1; 
    } 

这将允许您创建mob1并将其传递给您的主要方法。

0
public static void createMobile(String mobileName, String brand, String owner, int number){ 
      Mobile mobName = new Mobile(); 
      mobName.SetBrand(brand); 
      mobName.SetOwner(owner); 
      mobName.SetNumber(number); 
     } 

这里createMobile方法第一个参数的名称和移动对象名称相同的是,为什么你长了错误