在 Java 中,“定义参数”可以发生在多个场景,常见包括:方法参数、构造方法参数、泛型参数、命令行参数、注解参数等。下面按常见情况系统说明。
返回类型 方法名(参数类型 参数名, 参数类型 参数名...) {
// 方法体
}
public int add(int a, int b) {
return a + b;
}
int a、int b 就是方法参数public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
使用:
User user = new User("Tom", 18);
void change(int x) {
x = 10;
}
void change(List<String> list) {
list.add("A");
}
public void printAll(String... args) {
for (String s : args) {
System.out.println(s);
}
}
调用:
printAll("a", "b", "c");
⚠️ 规则:
public class Box<T> {
private T value;
public void set(T value) {
this.value = value;
}
}
使用:
Box<String> box = new Box<>();
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
运行:
java Main hello world
@interface MyAnnotation {
String value();
int count() default 1;
}
使用:
@MyAnnotation(value = "test", count = 3)
✅ 见名知意
✅ 避免单字母(除循环变量)
✅ 不使用保留字
❌ 不推荐:
void func(int a, int b)
✅ 推荐:
void calculate(int width, int height)
Java 参数 = 类型 + 名称,在方法、构造器、泛型或注解中定义,调用时按值传递。
如果你指的是某个具体场景(如 Spring 参数、HTTP 接口参数、Lambda 参数等),可以告诉我,我可以针对性讲解。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。