tilyougogannbare666

构造方法

功能:完成对象初始化的

当没有构造方法时,系统自动给一个构造方法

如果自定义了一个带参的构造方法,还需要使用无参的构造方法,就必须再写一个无参的构造方法

示例代码:

public class Student {//学生类
 private String name;
 private int age;
 public void setName(String name) {
  this.name=name;//用this修饰的是成员变量
 }
 public String getName() {
  return name;
 }
 public void setAge(int age) {
  this.age=age;
 }
 public int  getAge() {
  return age; 
 }
 public void show() {
  System.out.println(name+","+age);
 }
 public Student() {//无参的构造方法
  
 }
 public Student(int age) {//构造方法重载
  this.age=age;
 }
 public Student(String name) {
  this.name=name;
 }
}

----------------------------------

public class StudentDemo {//学生测试类
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //创建对象
  Student s=new Student();
  s.setName("ZG");
  s.setAge(12);
  s.show();
 
 Student s2=new Student(22);
 s2.show();
 Student s3=new Student("JF");
 s3.show();
 }
}
运行结果:
ZG,12
null,22
JF,0

分类:

技术点:

相关文章:

  • 2021-11-06
  • 2021-06-01
  • 2021-08-02
  • 2021-11-06
  • 2021-11-06
猜你喜欢
  • 2021-11-06
  • 2021-11-06
  • 2018-09-25
  • 2018-05-21
  • 2021-11-06
  • 2021-11-06
  • 2021-11-06
相关资源
相似解决方案