具有“void”的构造函数中的代码不执行 [英] Code in constructor with "void" not execute

查看:215
本文介绍了具有“void”的构造函数中的代码不执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用的话

class Test {
    public Test() {
        System.out.println("constructor");
    }
}

public class MainClass {
    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test();
    }
}

我得到2个输出
constructor
constructor

I get 2 outputs constructor constructor

但是如果我添加void到构造函数(public void Test()) - 输出为空。为什么这么奇怪?

But if I add void to constructor (public void Test()) - output is empty. Why is so strange ?

推荐答案

这并不奇怪,这是它的正常行为。构造函数没有返回类型

It's not strange, it's its normal behaviour. Constructor does not have a return type

public Test() {
    System.out.println("constructor");
}

是一个构造函数,但

public void Test() {
    System.out.println("constructor");
}

是一个简单的方法,您可以使用 t1 .Test()

is a simple method that you can call using t1.Test().

此页面列出了构造函数和方法之间的区别:

This page lists the differences between constructors and methods:


1)在Java中,方法与构造函数的第一个区别是构造函数的名称必须与类的名称相同,但在Java中没有这样的方法要求。方法可以在Java中具有任意名称。

1) First difference between method vs constructor in Java is that name of constructor must be same with name of the Class but there is no such requirement for method in Java. methods can have any arbitrary name in Java.

2)Java中方法和构造函数的第二个区别是构造函数没有任何返回类型,但方法有返回类型,

2) Second difference between method and constructor in Java is that constructor doesn't have any return type but method has return type and return something unless its void.

3)Java中的构造函数和方法之间的第三个区别是,构造函数被链接,它们按特定的顺序调用,没有这样的设施对于方法。

3) Third difference between constructor and method in Java is that Constructors are chained and they are called in a particular order, there is no such facility for methods.

4)与方法,构造函数不同,在类中声明的不是Class的成员。构造函数不会被子类继承,但方法是由子类继承的,直到它们被设为私有。在这种情况下,他们只有在他们被声明的类中可见。类似的私有构造函数意味着你不能从外部创建该类的对象,这是用于在Java中实现Singleton模式的一种技术。

4) Unlike method, constructor, yet declared in class doesn't considered as member of Class. Constructors are not inherited by child classes but methods are inherited by child classes until they are made private. on which case they are only visible in class on which they are declared. Similarly private constructor means you can not create object of that class from outside, this is one of the technique used to implement Singleton pattern in Java.

5)方法之间的另一个区别和构造函数在Java中是特殊的关键字this和super用于显式调用构造函数。没有这样的方法,他们有自己的名字,可以用来调用他们。

5) Another difference between method and constructor in Java is that special keyword this and super is used to call constructor explicitly. no such thing for method, they have there own name which can be used to call them.

这篇关于具有“void”的构造函数中的代码不执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆