在构造函数中使用一个变量 [英] using a variable in constructor in a method outside of constructor

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

问题描述

如果我有一个这样的构造函数:

if i have a constructor like so:

    public Constructor (int a, int b){

        int c =  a;
        int d =  b; 
    }

如何在同一个类中的方法中使用变量c和d

How can i then use variable c and d in a method within the same class as the constructor because trying to use just the variables name in the method doesn't seem to work?

推荐答案

实际上,你的代码将无法编译 - int c = int a 无效。

In fact your code will not compile - int c = int a is not valid.

我假设你的意思是: - int c = a;

I assume that you meant: - int c = a;.


方法在同一个类中
作为构造函数

How can i then use variable c and d in a method within the same class as the constructor

你不能,因为你已经声明它们作为范围结束的局部变量当构造函数结束执行时。

You can't because you have declared them as local variables whose scope ends when the constructor ends execution.

您应该将它们声明为实例变量。

You should declare them as instance variables.

public class MyClass {
    int c;
    int d;

    public MyClass(int a, int b){

        this.c = a;
        this.d = b; 
    }

    public void print() {
        System.out.println(c + " : " + d);
    }
}

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

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