乐鱼电竞

  • 教育行业A股IPO第一股(股票代码 003032)

    全国咨询/投诉热线:400-618-4000

    使用构造方法有哪些是需要注意的?

    更新时间:2021年09月01日18时33分 来源:乐鱼电竞 浏览次数:

    好口碑IT培训

    构造方法的创建 :

    如果没有定义构造方法,系统将给出一个默认的无参数构造方法,如果定义了构造方法,系统将不再提供默认的构造方法。 

    构造方法的重载 :

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

    推荐的使用方式

    无论是否使用,都手工书写无参数构造方法

    1630490825058_构造方法.jpg

    重要功能 :

    可以使用带参构造,为成员变量进行初始化

    示例代码

    /*
    学生类
    */
    class Student {
    private String name;
    private int age;
    public Student() {}
    public Student(String name) {
    this.name = name;
    }
    public Student(int age) {
    this.age = age;
    }
    public Student(String name,int age) {
    this.name = name;
    this.age = age;
    }
    public void show() {
    System.out.println(name + "," + age);
    }
    }
    /*
    测试类
    */
    public class StudentDemo {
    public static void main(String[] args) {
    //创建对象
    Student s1 = new Student();
    s1.show();
    //public Student(String name)
    Student s2 = new Student("林青霞");
    s2.show();
    //public Student(int age)
    Student s3 = new Student(30);
    s3.show();
    //public Student(String name,int age)
    Student s4 = new Student("林青霞",30);
    s4.show();
    }
    }



    猜你喜欢:

    Java中怎样定义和声明接口?

    Nginx return指令用法介绍【Nginx教程】

    搭建社群:确立搭建社群的目的?【新媒体培训】

    什么是对象?JavaSeript对象详细讲解

    乐鱼电竞Java高级软件工程师培训

    0 分享到:
    和我们在线交谈!
    【网站地图】【sitemap】