Java - define private fields using only one private keyword

隐身守侯 提交于 2019-12-12 21:45:37

问题


Is there a way for me to define private fields using only one private keyword? What I'm really asking is: is there something that I can do that looks like this:

private {
    int x;
    int y;
    Object myObject;
    //etcetera
};

and x, y, and myObject will all be created as private fields


回答1:


At least in java you can't do it like that. Because in java

There are several kinds of variables:

  1. Member variables in a class—these are called fields.
  2. Variables in a method or block of code—these are called local variables.
  3. Variables in method declarations—these are called parameters.

And each variables has its own Access Modifiers Like:

  1. public modifier—the field is accessible from all classes.
  2. private modifier—the field is accessible only within its own class.

So you have to do like following:

private int x,y;
private Object myObject;



回答2:


No. Its not possible to define variables of different datatypes in a single block. Closest is this:

private int x,y;
private Object myObject;


来源:https://stackoverflow.com/questions/14868284/java-define-private-fields-using-only-one-private-keyword

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!