在构造函数之外的构造函数中使用变量(using a variable in constructor in a method outside of constructor)

编程入门 行业动态 更新时间:2024-10-17 09:51:42
在构造函数之外的构造函数中使用变量(using a variable in constructor in a method outside of constructor)

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

public Constructor (int a, int b){ int c = a; int d = b; }

那我该如何在构造函数的同一个类中的方法中使用变量c和d,因为试图在方法中只使用变量名似乎不起作用?

if i have a constructor like so:

public Constructor (int a, int b){ int c = a; int d = b; }

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是无效的。

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

那我该如何在构造函数的同一个类中的方法中使用变量c和d

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

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

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); } }

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

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); } }

更多推荐

本文发布于:2023-07-18 04:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1154845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   变量   variable   constructor   method

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!