Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I highly suggest reading through the <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html" rel="nofollow">Java tutorial on classes and objects</a>, which will give you a good basis to work from.</p> <p>The most basic way to pass data between classes is to define public methods in your class that other objects can call to get access to your data. For example:</p> <pre><code>public class Person { private String firstName; private String lastName; public String getFirstName () { return firstName; } public String getLastName () { return lastName; } } </code></pre> <p>Methods with names like <code>getX()</code> that return values are called "getters". Then, in another class, you can access that data, for example:</p> <pre><code>public void elsewhere () { Person p = new Person(); System.out.println(p.getFirstName() + " " + p.getLastName()); } </code></pre> <p>Another way to communicate with classes is to write methods that take parameters, e.g.:</p> <pre><code>public void printFullName (Person p) { System.out.println(p.getFirstName() + " " + p.getLastName()); } public void elsewhere () { Person p = new Person(); printFullName(p); } </code></pre> <p>You may also want to provide methods to <em>set</em> data in an object. These are called "setters" and are the counterpart to "getters". Building on <code>Person</code> from above:</p> <pre><code>public class Person { private String firstName; private String lastName; public String getFirstName () { return firstName; } public String getLastName () { return lastName; } public void setFirstName (String firstName) { this.firstName = firstName; } public void setLastName (String lastName) { this.lastName = lastName; } } </code></pre> <p>Then, other objects can modify a person's data, e.g.:</p> <pre><code>public void elsewhere () { Person p = new Person(); p.setFirstName("Bob"); System.out.println(p.getFirstName()); // prints "Bob" } </code></pre> <p>Here's an example using everything from above:</p> <pre><code>public void swapPersonFirstAndLastName (Person p) { String temporary = p.getFirstName(); p.setFirstName(p.getLastName()); p.setLastName(temporary); } public void printFullName (Person p) { System.out.println(p.getFirstName() + " " + p.getLastName()); } public void example () { Person p = new Person(); p.setFirstName("John"); p.setLastName("Smith"); swapPersonFirstAndLastName(p); printFullName(p); // prints Smith John } </code></pre> <p>Hope that helps and good luck. Read those tutorials!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload