问题
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:
- Member variables in a class—these are called fields.
- Variables in a method or block of code—these are called local variables.
- Variables in method declarations—these are called parameters.
And each variables has its own Access Modifiers Like:
public
modifier—the field is accessible from all classes.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