[英]How to call objects in Java?
I am kind of embarrassed about this, and definitely I am just forgetting something simple. 我对此感到有些尴尬,当然我只是忘记了一些简单的事情。
if this is body.java 如果这是body.java
public class body{
public static void main(String args[])
{
int i = 0;
part aPart = new part(i);
aPart.add();
}
}
and this is part.java 这是part.java
public class part{
private int i;
public int part(int i)
{
this.i = i+10;
}
public add ()
{
i = i++;
System.out.println(i);
}
Why when i run javac to compile body.java, it says unknown symbol for part? 为什么当我运行javac来编译body.java时,它说部分未知符号?
because part is your constructor (you don't declare the return type as @amir said in his answer). 因为part是您的构造函数(您不必像@amir在他的回答中所说的那样声明返回类型)。 You should do 你应该做
public part(int i) {...}
as a note, Java convention is to have class names capitalized, so you should change your file to Part.java, your class declaration to "Part", and your constructor too... 值得注意的是,Java惯例是将类名大写,因此您应该将文件更改为Part.java,将类声明更改为“ Part”,并且将构造函数也更改为...
EDIT -- @coolbeans answer is correct too -- if your code in the question is correct, you are missing a closing brace. 编辑-@coolbeans答案也正确-如果问题中的代码正确,则缺少右括号。
javac *.java
吗?
Change your Part class like below:- 更改您的零件类,如下所示:-
public class Part{
private int i;
public Part(int i)
{
this.i = i+10;
}
public void add()
{
i = i++;
System.out.println(i);
}
}
And call it this way:- 并这样称呼:-
int i = 0;
Part aPart = new Part(i);
aPart.add();
You need to declare the constructor 您需要声明构造函数
public part(int i) {
this.i = i;
}
And to elaborate on what hvgotcodes said, constructors do not have a return type. 为了详细说明hvgotcodes所说的内容,构造函数没有返回类型。 The constructor of a Java class is not an ordinary method. Java类的构造函数不是普通的方法。 It's sole purpose is to instantiate an object of the the class which it belongs to. 唯一的目的是实例化其所属类的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.