【Java教程二十二】使用命令行参数和this

图片[1]-【Java教程二十二】使用命令行参数和this-安鹿轩-专注于资源创作于分享~

使用命令行参数

有时希望在运行程序时将一些信息传递给程序。它是通过将命令行参数传递给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


公告:快来抢广告位吧! 联系q:3533464073
© 版权声明

文章版权声明

1、本网站名称:安鹿轩

2、本站永久网址:www.anlu1314.com

3.安鹿轩(下文简称本站)提供的所有内容仅供学习、交流和分享用途,只供参考。

4.本站资源禁止并谢绝未经本站许可的使用,如若欲转载,请署名以及注明出处,请务必以文字链接的形式标明或保留文章原始出处和作者的信息。

5.本站(原创)文章、资源、图片等所有内容,一经转载,即表示您已经接受上述声明!需自行承担一切风险与责任!

6.关于本站的所有留言评论与转载、引用文纯属文字原作者个人观点,与本站观点及立场无关!

7.如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。

8.有任何侵权问题请联系E-mail [email protected]

THE END
感谢支持啦!୧( ⁼̴̶̤̀ω⁼̴̶̤́ )૭
点赞0 分享
让我来说两句( ˃̶̤́ ꒳ ˂̶̤̀ ) 抢沙发
头像
来来来,畅所欲言吧༼。^・ェ・^。༽
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容