java用类创建对象举例_用Java创建类的对象

使用三个步骤(即声明,实例化,初始化)从类中创建对象。首先用对象类型和对象名称声明对象,然后使用new关键字创建对象,最后调用构造函数以初始化对象。

演示对象创建的程序如下:

示例class Student {

int rno;

String name;

void insert(int r, String n) {

rno = r;

name = n;

}

void display() {

System.out.println("Roll Number: " + rno);

System.out.println("Name: " + name);

}

}

public class Demo {

public static void main(String[] args) {

Student s = new Student();

s.insert(101, "John");

s.display();

}

}

上面程序的输出如下-Roll Number: 101

Name: John

现在让我们了解上面的程序。

使用数据成员rno,名称和成员函数insert()和创建的Student类display()。演示此代码段如下:class Student {

int rno;

String name;

void insert(int r, String n) {

rno = r;

name = n;

}

void display() {

System.out.println("Roll Number: " + rno);

System.out.println("Name: " + name);

}

}

在该main()方法中,创建了Student类的对象。然后insert()使用参数101和“ John”调用方法。最后,该display()方法被调用。演示这的代码片段如下-public class Demo {

public static void main(String[] args) {

Student s = new Student();

s.insert(101, "John");

s.display();

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值