我可以在公共方法中声明私有变量吗? [英] Can I Declare private variables inside a public method?

查看:230
本文介绍了我可以在公共方法中声明私有变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是我在一次采访中问的.

我们可以在公共方法中声明私有变量吗?
如果可以,我们可以通过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屋!

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