1 class Person { 2 private String name; 3 private int age; 4 public String getName() { 5 return this.name; 6 } 7 8 public void setName(String name) { 9 this.name = name; 10 } 11 12 public int getAge() { 13 return this.age; 14 } 15 16 public void setAge(int age) { 17 this.age = age; 18 } 19 20 public int getAge() { 21 return this.age; 22 } 23 24 public String toString() { 25 return "姓名: " + this.name + ", 年龄: " + this.age; 26 } 27 } 28 29 public class InstanceDemo01 { 30 public static void main(String args[]) { 31 Class<?> c = null; 32 try { 33 c = Class.forName("Person"); 34 } catch(ClassNotFoundException e) { 35 e.printStackTrace(); 36 } 37 38 Person per = null; 39 try { 40 per = (Person)c.newInstance(); // 实例化Person对象 41 } catch(Exception e) { 42 e.printStackTrace(); 43 } 44 45 per.setName("李兴华"); 46 per.setAge(30); 47 System.out.println(per); // 内容输出: 调用toString() 48 } 49 }
时间: 2024-11-25 13:26:04