Java中构造函数的作用是什么?

23

构造函数的目的是什么?我在学校学习Java,到目前为止似乎构造函数在我们所做的事情中大多是多余的。尽管目的尚未明确,但到目前为止,它对我来说似乎没有意义。例如,下面两个代码片段之间有什么区别?

public class Program {    
    public constructor () {
        function();
    }        
    private void function () {
        //do stuff
    }    
    public static void main(String[] args) { 
        constructor a = new constructor(); 
    }
}

这是我们在作业中学习的做事方法,但是下面的方法不是可以达到同样的效果吗?

public class Program {    
    public static void main(String[] args) {
        function();
    }        
    private void function() {
        //do stuff
    }
}

构造函数的目的让我感到困惑,但是迄今为止我们所做的一切都非常基础。


10
这不是一个构造函数。实际上,它根本没有构造类的功能。一个构造函数看起来像public Program(){\\...,并且会被调用new Program() - AJMansfield
12个回答

1

构造函数有助于防止实例获取不真实的值。例如,设置一个包含身高和体重的Person类。不能有身高为0米,体重为0千克的人。


0

假设我们正在存储3名学生的详细信息。这三位学生的“sno”,“sname”和“sage”有不同的值,但全部属于同一个“CSE”部门。因此最好在构造函数内初始化“dept”变量,以便所有3个学生对象都可以使用该值。

为了更清楚地理解,请参见下面的简单示例:

class Student
{
    int sno,sage;
    String sname,dept;
    Student()
    {
        dept="CSE";
    }
    public static void main(String a[])
    {
        Student s1=new Student();
        s1.sno=101;
        s1.sage=33;
        s1.sname="John";

        Student s2=new Student();
        s2.sno=102;
        s2.sage=99;
        s2.sname="Peter";


        Student s3=new Student();
        s3.sno=102;
        s3.sage=99;
        s3.sname="Peter";
        System.out.println("The details of student1 are");
        System.out.println("The student no is:"+s1.sno);
        System.out.println("The student age is:"+s1.sage);
        System.out.println("The student name is:"+s1.sname);
        System.out.println("The student dept is:"+s1.dept);


        System.out.println("The details of student2 are");`enter code here`
        System.out.println("The student no is:"+s2.sno);
        System.out.println("The student age is:"+s2.sage);
        System.out.println("The student name is:"+s2.sname);
        System.out.println("The student dept is:"+s2.dept);

        System.out.println("The details of student2 are");
        System.out.println("The student no is:"+s3.sno);
        System.out.println("The student age is:"+s3.sage);
        System.out.println("The student name is:"+s3.sname);
        System.out.println("The student dept is:"+s3.dept);
    }
}

输出:

学生1的详细信息为:
学生编号:101
学生年龄:33
学生姓名:约翰
学生系别:计算机科学与工程
学生2的详细信息为:
学生编号:102
学生年龄:99
学生姓名:彼得
学生系别:计算机科学与工程
学生3的详细信息为:
学生编号:102
学生年龄:99
学生姓名:彼得
学生系别:计算机科学与工程


1
请查看 https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks 以了解在stackoverflow中的格式设置。 - Arun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接