Java - call a variable from another class -



Java - call a variable from another class -

within main method i'm trying understand how phone call variable different class.

i've attempted break downwards simple solution possible can head around logic involved.

i have 2 classes within bundle "var":

class 1 - source.java

package var; public class source { int source1; class setsource{ int source1 = 5; } }

class 2 - var.java

package var; public class var { public static void main(string[] args) { int var; var = source.setsource(); } }

first time post here i've spent 4 days , spare time trying figure out, please gentle i'm dedicated extremely newbie right now. in advance, hope i've submitted correctly.

okay, can sort of see thinking you've got of semantics incorrect. want define method. method takes next structure:

<access modifier> <return type> <method name> (<method arguments>)

so example

public void dosomething(string value) { // public method returns nothing. called dosomething // expects string value phone call "value" }

in case, want create 1 of these, , want create setter , getter (or accessor , mutator if you're beingness posh).

your setter

this normal method. purpose set value of class field. let's define our class..

public class myclass { private int num; }

now we've got class myclass field num. oh no, it's private, let's create setter user can update value.. next our formula methods, start public access modifier. define homecoming type, void because returns nothing. name of method should follow java naming convention, word "set" followed name of fellow member , value setter.. or together:

public void setnum(int num) { this.num = num; }

this update value in class value pass in. excellent!

your getter

well, nice , simple. next our formula, method public because can access it; returns (in case int) homecoming type; name follows convention of "get" followed name , expects no parameters.

public int getnum() { homecoming num; }

this homecoming value of num.

finally, using them!

public class mainclass { public static void main(string[] args) { myclass myclass = new myclass(); // create new myclass instance. myclass.setnum(4); // update value in class number 4. system.out.println("the number " + myclass.getnum()); // outputs: "the number 4" } }

java

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -