Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Lewis Evans   on May 05 In Java Category.

  
Question Answered By: Isabelle Brown   on May 05

If you are programming in Java, you do not have
"a program that at the moment uses no objects at
all"! A class  definition in Java becomes an Object upon
instantiation. Even the application module with the main()
method is an object, once you run it. The best
way to pass variables  is to write a method that
returns the variable: public String getVariableX()
{return X;} where X is the string you are
returning. You could write a method that returns all strings in
an array: public String[] getVariables() {//build
array and return it} a third way is to simply
return the Object and let the calling code extract the
individual object variables. public SourceObj
getObject(){return sourceObj} where sourceObj is an instance of
SourceObj. You then extract the variables
directly: this.variable = sourceObj.variable; Many object oriented
folks don't approve of this final method because it
breaks the encapsulation philosophy of an
object. Here is some test code that shows 2 of the 3 ideas (I
used a long instead of a String variable). public
class TestObj { long end =
System.currentTimeMillis()+5, med = System.currentTimeMillis()+3, start
=
System.currentTimeMillis(); public TestObj (SourceObj sourceObj) {
System.out.println("Before"); System.out.println("start:"+this.start);
System.out.println("med:"+this.med);
System.out.println("end:"+this.end);
this.end=sourceObj.end; this.med=sourceObj.med;
this.start=sourceObj.start; System.out.println("After");
System.out.println("start:"+this.start);
System.out.println("med:"+this.med);
System.out.println("end:"+this.end); } public static void main (String[]
args)
{ SourceObj so = new SourceObj(); TestObj
newObj = new TestObj(so); System.out.println("source
start:"+so.getStart() );
System.out.println("SourceObj:"+so.getSourceObj().toString() );
} } class SourceObj { long end =
99,med = 50,start = 1; public SourceObj() {}
public long getStart() {return start;} public
SourceObj getSourceObj() {return this;} public String
toString() { return "SourceObj start:" + this.start + "
med:" + this.med + " end:" + this.end;
} } There are other ways to do it, but these just popped to
the top of my head.

Share: 

 

This Question has 9 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on passing variables Or get search suggestion and latest updates.


Tagged: