对此很陌生,所以我希望标题中的术语正确。
我正在尝试弄清楚如何创建将执行以下操作的实例方法:
--返回一个身份证号码。
--由于每个对象都是从类构造函数创建的(实例化?),因此会为其分配一个唯一的整数 ID 号。第一个 ID 号是 1,随着新对象的实例化,将分配连续的编号。
我能够找到执行上述操作的类/静态方法的示例,但是我无法弄清楚如何使用实例方法执行此操作。我的尝试如下:
class Coordinates
{
private int iD = 0;
private float xCoordinate;
private float yCoordinate;
public Coordinates()
{
//Asks for input and assigns it to the two variables below
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
yCoordinate = keyboard.nextDouble();
iD++;
}
public getiD()
{
return iD;
}
}
我的主要方法如下:
public class Machine
{
public static void main(String[] args)
{
Coordinates c1 = new Coordiantes();
Coordinates c2 = new Coordiantes();
Coordinates c3 = new Coordiantes();
System.out.println("ID: " + c1.getID());
System.out.println("ID: " + c2.getID());
System.out.println("ID: " + c3.getID());
}
}
请注意,为了简单易懂,我没有包含我的全部代码。我希望我已经添加了足够多的内容。
我也不想使用 java.util.UUID。
最佳答案
现在的问题是您的“id”是一个实例变量,意味着它属于您创建的对象。 想一想,每次创建对象时,都会创建实例变量的新副本。 因此,每次创建对象时,id 首先设置为 0,然后递增一次(因此所有对象的 id=0)。
如果你想创建一个变量,比如说,自动计算你在类中创建的所有对象或具有 id,你需要创建一个类变量。 这些变量属于您从类中创建的所有对象,用于该类的关键字是“静态”。
注意:我使用的是静态变量,但不是静态方法。如果你根本不想使用static,那就另当别论了
class Coordinates
{
private static int count = 0;
private int id=0;
private float xCoordinate;
private float yCoordinate;
public Coordinates()
{
//Asks for input and assigns it to the two variables below
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the X Coordinate followed by the return key");
xCoordinate = keyboard.nextDouble();
System.out.println("Please enter the Y Coordinate followed by the return key");
yCoordinate = keyboard.nextDouble();
id=count++;
}
public getiD()
{
return iD;
}
}
只需更改关键字即可使您的程序正确无误。你不必做太多复杂的事情。
一开始很难掌握类和对象、静态和实例变量的概念。如果您需要更多解释,请告诉我:)
关于Java 使用实例方法而不是类/静态方法为每个实例化对象创建唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35461651/