21xrx.com
2025-04-21 17:34:54 Monday
文章检索 我的文章 写文章
如何在JAVA中创建对象?代码案例给你答案
2023-06-15 00:34:09 深夜i     17     0
在JAVA中 使用new关键字可以创建对象 具体实现是调用类的构造方法下面是一个简单的案例:

在JAVA中,创建对象是非常常见的操作,尤其是在面向对象编程中,对象是代码的基础。那么,JAVA中如何创建对象呢?下面就给大家分享一下几种创建对象的方法和案例。

方法一:使用new关键字

在JAVA中,使用new关键字可以创建对象,具体实现是调用类的构造方法。下面是一个简单的案例:

public class Person {
  private String name;
  private int age;
  public Person(String name, int age)
    this.name = name;
    this.age = age;
  
  public void showInfo() {
    System.out.println("姓名:" + name + ",年龄:" + age);
  }
}
public class Test {
  public static void main(String[] args) {
    Person p = new Person("张三", 20);
    p.showInfo();
  }
}

方法二:使用Class类的newInstance()方法

除了使用new关键字,还可以使用Class类的newInstance()方法来创建对象,前提是该类必须有无参构造方法。下面是一个示例:

public class Person {
  private String name;
  private int age;
  public Person()
  
  public void setName(String name)
    this.name = name;
  
  public void setAge(int age)
    this.age = age;
  
  public void showInfo() {
    System.out.println("姓名:" + name + ",年龄:" + age);
  }
}
public class Test {
  public static void main(String[] args) throws Exception {
    Class clazz = Class.forName("com.example.Person");
    Person p = (Person) clazz.newInstance();
    p.setName("张三");
    p.setAge(20);
    p.showInfo();
  }
}

方法三:使用ObjectInputStream类的readObject()方法

ObjectInputStream类的readObject()方法可以读取对象,并返回Object类型,需要强制转换为具体类型。下面是一个使用案例:

public class Person implements Serializable {
  private String name;
  private int age;
  public Person(String name, int age)
    this.name = name;
    this.age = age;
  
  public void showInfo() {
    System.out.println("姓名:" + name + ",年龄:" + age);
  }
}
public class Test {
  public static void main(String[] args) throws Exception {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.txt"));
    oos.writeObject(new Person("张三", 20));
    oos.close();
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"));
    Person p = (Person) ois.readObject();
    p.showInfo();
    ois.close();
  }
}

以上就是几种常见的JAVA创建对象的方法,希望对大家有所帮助。

关键词:JAVA、对象、创建

  
  

评论区

    相似文章
请求出错了