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

来源:百度知道 编辑:UC知道 时间:2024/05/10 12:36:00
谢谢了

引用:
在这个程序里面的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

在类(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方法
}

}