用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();
   }
}