Java中的基本构造函数用法 [英] basic constructor usage in java

查看:58
本文介绍了Java中的基本构造函数用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论出于何种原因,我都无法在其他任何地方找到此问题,也无法在线找到答案。如果我具有以下条件:

For whatever reason, I cannot find this question anywhere else, nor can I find the answer online. If I have the following:

package temp1;

public class MainClass {

    public static void main(String[] args) {
    }

    public MainClass(int radius_x, int area_x, int circumference_x) {
        int radius = radius_x;
        int area = area_x;
        int circumference = circumference_x;
    }

}

假设这甚至是正确的用法,那么我该如何真正使用这里的构造函数中定义的变量?由于作用域,它们只能在构造函数内部工作。

Assuming that this is even correct usage, then how would I actually use the variables defined in the constructor here? They only work inside of the constructor thanks to scope.

推荐答案

您所提供的代码毫无意义,这是正确的。更常见的情况是使用构造函数初始化一些实例变量,然后可以在整个类中使用它们。

You are correct that the code you supply makes little sense. A more common scenario is to use the constructor to initialize a few instance variables, which can then be used throughout the class.

public class MainClass {
    private int radius;
    private int area;
    private int circumference;

    public static void main(String[] args) {
    }

    public MainClass(int radius_x, int area_x, int circumference_x) {
         this.radius = radius_x;
         this.area = area_x;
         this.circumference = circumference_x;
    }

}

这篇关于Java中的基本构造函数用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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