使用命令行参数
有时希望在运行程序时将一些信息传递给程序。它是通过将命令行参数传递给main()来实现的。
命令行参数是执行时在命令行上直接跟随程序名称的信息。 要访问Java程序中的命令行参数非常简单。 它们作为字符串存储在传递给main()的String类型数组中。
示例
以下程序显示传递给程序的所有命令行参数 -
public class CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i ) {
System.out.println("args[" i "]: " args[i]);
使用以下方式执行此程序 -
C:/> java CommandLine this is a command line 200 -100
那么将得到以下结果:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
0 2378 收藏
this
this是Java中的一个关键字,用作对当前类对象的引用,在实例方法或构造函数中。 使用它可以引用类的成员,例如:构造函数,变量和方法。
注 - this关键字仅在实例方法或构造函数中使用。
通常,this关键字用于 -
如果实例变量在构造函数或方法中具有相同的名称,则将它们与局部变量区分开来。
class Student {
private int age;
Student(int age) {
this.age = age;
从类中的其他方法调用一种类型的构造函数(参数化构造函数或默认值),称为显式构造函数调用。
class Student {
int age
Student() {
this(20);
Student(int age) {
this.age = age;
以下是使用this关键字访问类成员的示例 -
public class ThisExample {
// 实例变量:num
int num = 10;
ThisExample() {
System.out.println("This is an example program on keyword this");
ThisExample(int num) {
// 调用默认构造方法
this();
// 将局部变量 num 分配给实例变量 num
this.num = num;
public void greet() {
System.out.println("Hi Welcome to Yiibai");
public void print() {
// 局部变量:num
int num = 20;
// 打印局部变量
System.out.println("value of local variable num is : " num);
// 打印实例变量
System.out.println("value of instance variable num is : " this.num);
// 调用类方法
this.greet();
public static void main(String[] args) {
// 实例化该类
ThisExample obj1 = new ThisExample();
// 调用 print 方法
obj1.print();
//通过参数化构造函数将新值传递给 num 变量
ThisExample obj2 = new ThisExample(30);
// 再次调用 print 方法
obj2.print();
执行上面示例代码,得到以下结果 -
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Yiibai
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Yiibai

暂无评论内容