我可以在公共方法中声明私有变量吗? [英] Can I Declare private variables inside a public method?
问题描述
这个问题是我在一次采访中问的.
我们可以在公共方法中声明私有变量吗?
如果可以,我们可以通过public方法访问变量吗?
This question was asked from me in an interview.
Can we declare private variables inside a public method?
If can, can we access variables through the public method?
我尝试使用Java,但是不允许在方法内部定义私有变量,这是为什么?
I tried with java but it does not allow to define private variable inside a method why is that?
public class GetUser {
public String getUserName(){
private String user="David";
return user;
}}
推荐答案
不,您不能. 方法内部的变量被认为是局部的,不能有修饰符. 您可以在一个类中有专用字段,但这是不同的:
No, you can not. Variables inside method are considered local and can't have modifiers. You can have private fields in a class, but this is different:
public class Test {
public String getUserName(){
user="David";
return user;
}
private String user;
}
此外,命名类GetUser
有点尴尬.
更好的类名称为User
. getUser
更适合方法名称.
Besides, naming a class GetUser
is kind of awkward.
A better class name would be User
. getUser
is more appropriate for a method name.
这篇关于我可以在公共方法中声明私有变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!