使用新运算符在Java中创建类对象
可以使用new运算符在Java中创建类对象。新运算符通过为对象动态分配内存,然后返回对该内存的引用来实例化一个类。变量用于存储内存引用。
演示此过程的程序如下:
示例
class Student {
int rno;
String name;
public Student(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(15, "Peter Smith");
s.display();
}
}输出结果
Roll Number: 15 Name: Peter Smith
现在让我们了解上面的程序。
使用数据成员rno,名称创建Student类。构造函数初始化rno,name,然后方法display()打印其值。演示此代码段如下:
class Student {
int rno;
String name;
public Student(int r, String n) {
rno = r;
name = n;
}
void display() {
System.out.println("Roll Number: " + rno);
System.out.println("Name: " + name);
}
}在该main()方法中,使用new运算符创建了Student类的对象。该display()方法被调用。演示此代码段如下:
public class Demo {
public static void main(String[] args) {
Student s = new Student(15, "Peter Smith");
s.display();
}
}