在java中怎么定义一个方法?

谢谢了

第1个回答  2007-11-15
引用:
在这个程序里面的a.getx()自定义方法,就需要返回值.
因为前面的实例变量x为整型
所以返回值类型也要是整型
然后用return返回x的值50
用a.getx()调用
使用System.out.println();输出return返回来的值

public class Test{
private int x=50;
public int getx(){
return x;
}
public static void main(String[] args){
Test a=new Test();
System.out.println(a.getx());
}
}

运行结果为50本回答被提问者采纳
第2个回答  2007-11-15
在类(class)中定义:

eg: class test
{
public int a;
public int test(int b)
{
a=b;
}
public int get_a() //方法 1
{
return a;
}
public void print() //方法2
{
System.out.println(this.get_a());
}
public static void main(String [] args) //主函数
{
test aa=new test(3); //初始化 aa
aa.print(); //调用 print方法
}

}

参考资料:自己

相似回答