开发者

A question that's been bothering me for so long [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorica开发者_开发知识库l and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

can you return an array? or an array of objects? or return an object? is that really possible? or is that possible? can anyone give me examples? and also can anyone provied me any good links when it comes to good programming practice? OOP specifically since I want to be a good java programmer also can you return user defined classes? like objects with setters and getters? and arrays? and arrays of objects?

double Amounts ={1,2,3,4,5,6,7} 
for(int i = 0;i<Amounts.length;i++) { 
    Briefcase[i] cases= new Briefcase[]; 
    double x = Amounts[i];
    Briefcase[i].setValue(x); 
} 

public Briefcase[] get(){ 
    return Briefcase[]; 
}


Yes, in many different ways. Not exactly sure what you are asking, so here are a few examples.

public Object[] getArray() { }

public MyObject[] getArray() { }

public List<MyObject> getArray() { }


You need to be more specific. And I cant imagine how can the simple below code make someone bother so long :)

public MyObject[] getArray() {
    return new MyObject[10];
}


Here's a complete example of returning an array of user defined objects. HTH.

public class Example {
    public static class Composer {
        private final String name;

        Composer(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

    }
    public static void main(String... args) {
        Composer[] composers = getComposers();
        for (Composer composer : composers) {
            System.out.println(composer.getName());
        }
    }

    public static Composer[] getComposers() {
        return new Composer[]{new Composer("Mozart"), new Composer("Pachbel"),
                new Composer("Vivaldi")};
    }
}


Since java is Object oriented language , its made to play around using Objects. returning array and

an Object does't make any difference in java. An Array is an Object after all. So you can return

anything (I mean Arrays, Objects with getters Setters, or Any type of Objects). and that covers even

the classes you create since they are also Objects by default (Since every class you create in java

will Extend Object class by default).

for instance you can do this,

Class A{
private int[] arr = {1,2,3};

private A a;

public int[] getArray(){
return arr;
}
public void setA(){
a = new A();
}
public A getA(){
return a;
}

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜