How program passes values to method ranking() - java

Hi all,
I would like to ask you for help to understand logic of this program specially some parts that I am probably stack in.
1.Method ranking(). It doesn´t accept any parametr but returns result from parametrs "won" and "tied". OK. But when we call this method like this
System.out.println(adelaideCrows.getName()+": result:
"+**adelaideCrows.ranking()**);
how the program knows values of "won" and "tied" for this adealideCrows team? I know that OOP is about passing objects respective references to objects. So does it work so that when we firstly call method adelaideCrows.matchResult(ohioFotlball, 1,0); then adelaideCrows is the reference to method matchResult passing there parametres in brackets and then they are stored in memory under reference of adelaideCrows? so when we next call the same method with another reference melbournSoccer.matchResult(newyorkSoccer,6,4); then parametres "won" and "tied" have their own values passed in brackets under reference melbournSoccer? So after calling method ranking() with reference e.g. adelaideCrows program knows that under this reference there are already stored values of parametres "won" and "tied" and method then returns correct values. Right?
2.And also here System.out.println(melbournSoccer.compareTo(newyorkSoccer)); Does the logic is the same? melbournSoccer reference is connected in method public int compareTo(Team<T> team) to this.ranking() but reference newyorkSoccer is connected to team.ranking()? So calling this.ranking() invokes values stored in memory of reference melbournSoccer and so on?
Thank A LOT.
Here is the code for Main class:
public class Main
{
public static void main(String[] args) {
SoccerPlayer soccerPlayer = new SoccerPlayer("joe");
BaseballPlayer baseballPlayer = new BaseballPlayer("pat");
FootballPlayer footballPlayer = new FootballPlayer("backham");
Team<FootballPlayer> adelaideCrows = new Team<>("Adelaide Crows
footbal");
Team<SoccerPlayer> melbournSoccer = new Team<>("Melbourn soccer");
Team<BaseballPlayer> jerseeBaseball = new Team<>("Jersee
Baseball");
melbournSoccer.addPlayer(soccerPlayer);
jerseeBaseball.addPlayer(baseballPlayer);
adelaideCrows.matchResult(ohioFotlball, 1,0);
melbournSoccer.matchResult(newyorkSoccer,6,4);
System.out.println("Ranking...");
System.out.println(adelaideCrows.getName()+": result:
"+adelaideCrows.ranking());
System.out.println(melbournSoccer.getName()+": result:
"+melbournSoccer.ranking());
System.out.println(jerseeBaseball.getName()+": result:
"+jerseeBaseball.ranking());
System.out.println(melbournSoccer.compareTo(newyorkSoccer));
System.out.println(adelaideCrows.compareTo(ohioFotlball));
Player class here from which another three classes FotballPlayer, SoccerrPlayer and BaseballPlayer inherits.
public abstract class Player{
private String name;
public Player(String name){
this.name = name;
}
public String getName(){
return name;
}
}
And here is Team class.
import java.util.ArrayList;
public class Team<T extends Player> implements Comparable<Team<T>>{
private String name;
int played = 0;
int lost = 0;
int won = 0;
int tied = 0;
private ArrayList<T> members = new ArrayList<>();
public Team(String name){
this.name = name;
}
public String getName(){
return name;
}
public boolean addPlayer(T player){
if(members.contains(player)){
System.out.println(player.getName()+" is already on this
team.");
return false;
}else{
members.add(player);
System.out.println(player.getName()+" has been added to team
"+this.name);
return true;
}
}
public int numPlayers(){
return this.members.size();
}
public void matchResult(Team<T> oponent, int ourScore, int theirScore){
if(ourScore > theirScore){
won++;
}else if(ourScore == theirScore){
tied++;
}else{
lost++;
}
played++;
if(oponent != null){
oponent.matchResult(null, theirScore, ourScore);
}
}
public int ranking(){
return (won * 2) + tied;
}
#Override
public int compareTo(Team<T> team){
if(this.ranking() > team.ranking()){
return -1;
} else if(this.ranking() < team.ranking()){
return 1;
}
else{
return 0;
}
}
}

Here are some clarifications to the questions.
Question 1:
Method ranking(). It doesn´t accept any parametr but returns result
from parametrs "won" and "tied". OK. But when we call this method like
this:
System.out.println(adelaideCrows.getName() + ": result: " + **adelaideCrows.ranking()**);
how the program knows values of "won" and "tied" for this
adealideCrows team? ...
Answer 1:
Consider this statement in the Main class: adelaideCrows.matchResult(ohioFotlball, 1, 0);. When this statement executes:
The adelaideCrows object gets affected. In the matchResult method the
instance variables won and tied are changed based on the method input
parameters (1 and 0, in this case).
When the statement adelaideCrows.ranking() is executed, the ranking() method uses the adelaideCrows's object instance variables won and tied (which were set earlier) to calculate the ranking ((won * 2) + tied) and return the value.
NOTES: See this article (my answer) on StackOverflow to get an idea about a Java class, an object, a reference, and class's attributes and behavior: Object References in Java.
Question 2:
And also here
System.out.println(melbournSoccer.compareTo(newyorkSoccer)); Does the
logic is the same? melbournSoccer reference is connected in method
public int compareTo(Team<T> team) to this.ranking() but reference
newyorkSoccer is connected to team.ranking()? So calling
this.ranking() invokes values stored in memory of reference
melbournSoccer and so on?
Answer 2:
Consider the statement: System.out.println(melbournSoccer.compareTo(newyorkSoccer));
Q). melbournSoccer reference is connected in method public int compareTo(Team<T> team) to this.ranking()
A). The keyword this refers to the current object - here it is melbournSoccer. this.ranking method gets the ranking for the melbournSoccer.
Q). Reference newyorkSoccer is connected to team.ranking()?
A). The method parameter compareTo() takes a Team as input - here it is a newyorkSoccer team object.
Q). So calling this.ranking() invokes values stored in memory of reference melbournSoccer and so on?
A). YES.
NOTES: Here is a link to Oracle's Java tutorials topic Using the this Keyword.

I try to answer your first question: The variables „won“ and „tied“ are instance variables. That means every time you create an object of your team class, the object gets its own „won“ and „tied“ variable to save data in it. You can access them with the name of the unique object (in your case the team name as example „adelaideCrows.won“ without the quotes). To answer the question about the „matchResult“ function: The function is related to your object again because you are not using „static“ declaration in front of the method name. So without static every instance of your class gets their own method so if you are passing parameters to that function they are passed into the objects function. If you want to save them you have to create a class variable (which is made with „static int“ as example) or a instance variable in order to save the data as long as the object exists, otherwise the data will get passed to the function and will be lost after the function execution is finished.

Related

Use the result set of a class method into another class method

i have a class A in which there is a method Method1, in Method1 i want to pass the "rs" to class B method. how can i do it? try different things but unsuccessful.
Note: I did not write the full method code just gave an scenario to find the solution from you.
public class A {
Resultset rs = null;
public void method1() {
this.rs = this.stmt.executeQuery(this.query);
// while (this.rs.next()) {
// int id = rs.getInt("node_Id");
// String name = rs.getString("node_Name");
// String par = rs.getString("node_Parent");
// int lvl = rs.getInt("node_Level");
// System.out.println(+id+" "+name+" "+par+" "+lvl);}
if (success == 0) {
this.conn.rollback();
} else {
System.out.println("rs" + rs);
this.conn.commit();
}
}
now i want to use the variables id,name,par,lvl in another class method like
following
public class B{
public void usage(){
//in here i want to get the varibles id,name,par,lvl
}
}
Right now, you made these variables to be local variables within method1() (which is by the way a really bad name for a method - always use names that mean something, even in examples).
Because of that, you can only pass them around, by well, passing then, such as
B someB instance = ... // however that gets created
while (this.rs.next()) {
int id = rs.getInt("node_Id");
someB.doSomethingWith(id);
That's it. But the better approach would be to have, say a class C that wraps around all the information you want to pass around.
Then instead of creating and passing the individual values, you would collect the required values, and use those to create an instance of your new C class. And then you pass that object to whatever method that is going to need it.

Trying to understand Abstract class inheritance and subclass object comparison

I'm working on a project for my data structures class and I've been having a hard time wrapping my head around Abstract class inheritance and how it can be manipulated through subclasses, object comparison, method args, etc. I've been reading through Stack Overflow posts and Java tutorials, and while I've learned a ton, I'm still not understanding some things. I haven't coded in Java in 2+ years and have been using mostly C lately so I'm feeling very rusty and overwhelmed.
Project Overview
I was asked to build a database of sorts that represents data for my university students and professors. I have an abstract superclass, Person, which has 2 child classes Student and Instructor. Lastly (the class I'm currently working on), is a class called UniversityPeople which references an array of Student[] objects as well as an array of Instructor[] objects. The UniversityPeople class has methods to add(), delete(), search(), validate data, ect. for the 2 object arrays.
I know this implementation seems really strange, but I have to follow the instructions unfortunately. I've tried to make the methods work with both arrays seamlessly which is partially where I'm getting confused. Here are my questions:
1.) This is kind of a general question, but one I feel is important to understanding inheritance. I've done tons of reading on this, but I'm still pretty confused. If I create an object that uses the type of the superclass but is a subclass object, like: Person newStudent = new Student(), will this object have access to the methods in it's own class, or is it restricted to the superclass methods only? My understanding was, if the superclass is abstract, the children still inherit their methods when instantiated in this way.
2.) I don't understand how to differentiate between the two object arrays in the methods. For example, I'm writing a clear() function that sets the specified object array(Student[] or Instructor[]) to null when called. I first tried using the instanceOf method to test what type the array was but the compiler warned me I couldn't cast type Student to Person or something like that. Here is the constructor for the class as well as the clear function I'm having trouble with. I'm not sure if I'm understanding how inheritance fully works here, so if there's a better way please enlighten me:
Constructor:
//Global declarations
//Declares arrays of student and instructor classes
private Student[] studentArray;
private Instructor[] instArray;
private int studentCount;
private int instCount;
/*
checks user input. If user enters 1, create student array.
if user enters 2, create Instructor array
*/
public UniversityPeople(int type, int size)
{
if (type == 1)
{
studentArray = new Student[size];
}
else if (type == 2)
{
instArray = new Instructor[size];
}
}
Separate insert methods for students/instructors because I couldn't figure out a way to do 1, if it's even possible:
/*
checks if array is full or duplcate id exists.
If not, new Student object is created and
inserted into the student array
*/
public void insertStudent(String lastName, String firstName, int id,
int age, String yearStanding, double GPA)
{
boolean checkFull = isFull();
boolean checkId = containsID(studentArray, id);
if (checkFull)
{
System.out.println("Array is full. Please delete a data member.");
}
else if (checkId)
{
System.out.println("Duplicate ID. Please check data and re-enter.");
}
if (!checkFull && !checkId)
{
Student newStudent = new Student(lastName, firstName, id, age, yearStanding, GPA);
newStudent = studentArray[studentCount];
studentCount++;
}
else
System.err.println("There was an error while attempting to \n" +
"process your request. Please check your \n" +
"data entry and try again.");
}//end insertStudent
/*
checks if array is full or duplicate id exists.
If not, new Instructor object is created and
inserted into instructor array
*/
public void insertInstructor (String lastName, String firstName, int id,
int age, int officeNum, String subjectTaught)
{
boolean checkFull = isFull();
boolean checkId = containsID(instArray, id);
if (checkFull)
{
System.out.println("Array is full. Please delete a data member.");
}
else if (checkId)
{
System.out.println("Duplicate ID. Please check data and re-enter.");
}
if (!checkFull && !checkId)
{
Instructor newInstructor =
new Instructor(lastName, firstName, id, age, officeNum, subjectTaught);
newInstructor = instArray[instCount];
instCount++;
}
else
System.err.println("There was an error while attempting to \n" +
"process your request. Please check your \n" +
"data entry and try again.");
}//end insertInstructor
Lastly, a method to find someone in the array from their id and a method to clear whatever array is specified. I've made the arg type Person[] array in most of these methods which I hope is acceptable.
public int findPerson(Person[] array, int id)
{
for (int i = 0; i < array.length; i++)
{
if (array[i].getId() == id)
{
return i;
}
}
return -1;
}
//Sets specified array to null. I need to reset the count of objects in
//the specified array to 0, but i'm really confused about how that works. Below is the best
//understanding I could come up with
public void clear(Person[] array)
{
for (int i = 0; i < array.length; i++)
{
array[i] = null;
}
if (array.getClass().equals(Student.class))
{
studentCount = 0;
}
else if (array.getClass().equals(Instructor.class))
{
instCount = 0;
}
else
{
System.out.println("There was an issue validating the object type.");
}
}
I'm especially confused about the implementation of the clear() method as I've never had to do this type of object comparison before. I'm not sure why the instanceOf operator comparison was giving me weird results.
[...] will this object have access to the methods in it's own class, or is
it restricted to the superclass methods only? My understanding was, if
the superclass is abstract, the children still inherit their methods
when instantiated in this way.
It doesn't matter, whether the superclass is abstract. A child class inherits the parent class' methods and attributes. Whether these are accessible by the child class depends on visibility modifiers.
I'm having a hard time understanding how to differentiate between the
two object arrays in the methods. For example, i'm writing a clear() function that sets the specified object array(Student[] or Instructor[]) to null when called.
You could overload the clear() method like:
public void clear(Student[] array) {...}
public void clear(Instructor[] array) {...}
or (if I understand the purpose of your example correctly) compare the input array's reference with the array references in your class definition:
public void clear(Person[] array) {
if(array == this.studentArray) {
// clear students
} else if(array == this.instArray) {
// clear instructors
}
}
But if you want to actually compare the arrays' types, you can do:
array.getClass().equals(Student[].class)
or
array instanceof Student[]
For the clear method :
array = new Person[array.length] // re-init arrayt ot it's inital size.
studentCount = studentArrayl.length;
instCount = instArray.length;
that should réinit the given array to a new empty array of the correct length and reasigne correct number to studentCount and instCount.
Regards.
Nemesis.
For #1, yes, newStudent will have access to it's own methods and also it's superclass unless it's #Overriden.
For #2, you are having a hard time because your UniversityPeople class is doing too many things. This is will become a maintenance issue and is a code smell. UniversityPeople violates the single responsibility principle. Your class should do one thing only. Why not do a UniversityInstructor and a UniveristyStudent? But since you are following instructions, here's an idea for your clear function. Before you null your array, get one content in the array. Say Person person = array[0];, then you can do an if (person instanceof Student) and then if (person instanceof Instructor). This way you'll know the type of you array and proceed accordingly.

Stack variables in Java (newbie)

I am staring to study java and currently I am learning about the classes setters.
I see that the most common way to make a setter is something like this.
class Apple{
private String _name;
//Setters
public void setName(String name){
_name = name;
}
}
I am used to C so this code raises me a question. If I am setting _name = name in a function, after this function is completed and his stack is discarded why does the variable _name still stores the right value? This is confusing because in C if I assig a pointer to another pointer inside a function like this it would probably cause a segmentation fault (since name is a temporary variable).
In Java, you as an user don't have control over the stack as in C/C++ languages.
In addition, all non-primitive data types (int, double, etc.) are stored in the heap. The user is only able to use references or pointers and is not required to perform any kind of memory management, since a mechanism known as garbage collector already frees those instances which haven't any reference to them. Therefore, there are no such thing as pointers in Java, although you can assign a null value to a non-primitive variable: Foo f = null;
Therefore, in Java you could literally behave what this C++ code does:
class Foo {
Foo( int a ) {}
};
void bar( int a ) {
Foo f(a); // f is placed in the stack
}
The only way you can create an instance of Foo in java would be like this:
void bar( int a ) {
Foo f = new Foo(a); /* f is a reference to the new instance
* (placed in heap) */
}
Actually, name is an instance variable and setName() is an instance method. This means that there is a separate copy of name for every object of the class Apple. The setName() method sets the value for the global variable of the object it is called with to that of its argument. So, even after the stack of the method is discarded, the object exists and so does the value of this object's copy of name. See this example below:
class Apple {
private String name; //instance variable
public void setName(String name) {
this.name = name; //same as what you have written
}
//main method
public static void main(String[] args) {
Apple obj = new Apple(); //object created
Apple obj2=new Apple();
obj.setName("Yolo");
obj2.setName("Yay!");
System.out.println(obj.name); //displays obj's copy of name that holds the value "Yolo"
System.out.println(obj2.name); //displays obj2's name
}
}
This displays
Yolo
Yay!
I hope this makes it clear to you.
You are setting the reference of name to the reference of _name so they look in the same spot in memory. Therefore when the instance of setName disappears and the variable name with it the reference stored in _name remains.
Since you set _name to private it can only be accessed inside the class Apple. You cant change it within your main method and that's why you create the set method so it can be changed by outside classes (I.e. Your main method)

What does "void" mean as the return type of a method? [duplicate]

This question already has answers here:
Can someone explain a void return type in Java?
(5 answers)
Closed 6 years ago.
I'm confused about "void",
as it pertains to methods.
I don't know what the distinction between two methods is when one has "void" and another doesn't.
For example, if I do:
Public meth (int amount)
{
amount = initial * interest;
return amount;
}
( not sure if it was right, or even valid, to take the name "amount" and name it the same thing as my formal parameter, but what makes sense here is that you're performing a calculation and returning the result)
Then, if I did something like:
Public void Testing (int array[])
{
//code that would modify the internals of an array
}
Would the second one have no "return" because it's more of a general method, that can be applied to any integer array, while the first one is about doing work on specific variables?
Would also appreciate one or two more examples of when I would or wouldn't be using "void" and "return".
One other thing that seems to confuse me is calling methods.
I know sometimes I'll do something like, for example, using the Testing method above,
Testing(ArrayName);
Other times, it will be like:
NameOfWhateverImApplyingMethodTo.MethodName();
And then there are times when things will be done properly by:
Thing1.MethodName(Thing2);
Which circumstances would I switch the syntax for method calls like this?
Java is case sensitive, so the modifier Public is invalid, use public
You can't define a method as public methodName(int a), only a constructor has this signature, a method must be public void methodName(<signature>) for methods that don't return anything or public <return type> methodName(<signature>) for methods that do.
Void basically means that the method will not return anything.
If you did
String name= "tim";
public void getName(){
return name;
}
This would result in an error, because the getName method is returning a string object called name, but the method declaration is saying I am returning nothing - because it is void.
Instead the method should be :
String name = "tim";
public String getName(){
return name;
}
Now when the method getName() is called it will return a string object "name" with "tim" inside of it :)
You might have void for a set method. So for example
String name = "tim";
public void setName(String newName){
this.name = newName;
}
When this method is called you would use setName("Andy"); and it would set the value of the name variable to be "Andy". Nothing is returned in this method, because it is setting something, but there is no need to send anything back, so we use void on the method declaration.
Hope this helps.
The method that has void as return type does not return anything. For example you want to set a field firstName in your class. You will write a setting method like
public void setFirstName(String n) {
this.firstName = n;
}
As you can see you are just setting a class variable and does not require to return anything.
If you dont use void then you have to provide a return type for method. Like if you wish to write a getter for above variable as:
public String getFirstName() {
return this.firstName;
}
Once you provide a return type, you will have to return a value of that type otherwise your code will not compile.
Calling a method can be done based on where you are calling it from and what modifier is used:
If you are calling the method from the same class then you can simply write firstName = getFirstName()
If you are calling the method from another class then you require object of method's class as qualifier like personObject.getFirstName()
If you are calling a static method then you require class name as qualifier like Person.getFirstName();
Return type is what you get out of it. When you call it, what are you hoping to get back? For instance, if the method gets the average of two numbers, then you're expecting a number back, so the return type will be a number type, like "int" (integer).
You can see what it should be using that logic or by looking in the method for the word return - what comes after return is what is returned, and its type should be declared in the method (e.g. if it says "return 4;" it's returning an int, and should be e.g. public int getFour()
You also asked about e.g. testing() vs testing(word)
I remember having the same difficulty. The distinction between the two also relates to the method declaration line. I'll illustrate.
public String testing(){
return "a word";
}
Calling this method by doing "System.out.println(testing());" should print "a word". Calling this method by doing "System.out.println(testing("a word"));" will give you an issue - this is because when you call testing, it looks at the appropriate method: one in the right class, with the right return type and with the right arguments/parameters. If you're calling testing("a word"), that means you're using a String as an argument (because "a word" is a string), and so it tries to use the testing(String aString) method - which doesn't exist.
So you use empty brackets when the method takes no input, and you put stuff in brackets when the method expects stuff. This should be less confusing than it sounds, because it's usually logical - if you want to call a method that returns an average, you need to ask yourself "Average of what?" You'd probably need to supply it with the values you want the average of.
Moving on: (a) testing() versus(b) AClass.testing() versus(c) aclass.testing() -
In (a), there's no class specified. Therefore, if you call it from that class, Java can guess which class: this one, and it'll work. From any other class, it won't know what you're talking about, and might even insult you.
In (b), you're specifying a class in general - therefore it'll know what class to find it in - and it'll work if it's a "static method". *[see bottom]
In (c), you're specifying an instance of AClass you want to run "testing()" on*.
For instance, imagine you've created a class called Business. You make a hundred Business objects by specifying for each a name, number, address.
e.g.
Business b = new Business(name, number, address);
Then in the Business class you have a method "getName()". This method takes no argument - you could see that the brackets are empty - so if, from another class, you call "Business.getName()", how could it know which name you want? You've just made a hundred businesses!
It simply can't. Therefore, for such a method, you'd call "b.getName()" (b being the Business we created above) and it would get the name for this instance of a Business - namely, b.
I'm happy to help, so if you're confused about any particular parts of what I just wrote please let me know and I'll try to elaborate!
edit: A bit on static methods:
Static methods don't belong to an instance of the class. getName(), for example, would get the name of this Business - ie, this instance of the Business class. But let's say that in the Business class you made a method that took the first letter of each word in a String and transformed it to uppercase - like if you wanted to make the business names look more professional when you printed them out.
public static String stringToUpperCase(String aString){
aString = aString.substring(0, 1).toUpperCase() + aString.substring(1);
return aString;
}
And to use that, you change the getName() method from:
public String getName(){
return name;
}
to
public String getName(){
return stringToUpperCase(name);
}
The new method is used here to make the name have an uppercase first letter - but that is the extent of its involvement with the Business class. You notice it doesn't ask for information about the name, address, or number for a particular business. It just takes a string you give it, does something to it, and gives it back. It doesn't matter whether you have no Businesses or a hundred.
To call this method, you'd use:
System.out.println(Business.stringToUpperCase("hello"));
This would print Hello.
If it were not a static method, you'd have to make a new Business first:
Business b = new Business("aName", "aNumber", "anAddress");
System.out.println(b.stringToUpperCase("hello"));
And if the method did need access to more Business-instance information (like a business's name number or address) it wouldn't be able to be an instance variable.
The first example, a method without a return type at all, is a constructor; used when an instance is created with new. However, you can't return a value from a constructor. Something like,
this.amount = initial * interest; // return amount;
Sets the field amount to initial * interest.

Java Object Reference and Java Methods

I am unable to understand how this works
public void addToRule(Rule r) {
if (!getRuleList().contains(r)) {
getRuleList().addElement(r);
}
}
If I run this code:
obj.addToRule(r);
System.out.println(getRuleList().contains(r));
it prints out true how can this happen?
btw ruleList is a vector member of the main class and is not a static variable(don't think this matters but sharing anyway).
import java.util.Vector;
public class RuleEngine{
private Vector ruleList = new Vector();
public Vector getRuleList(){
return ruleList;
}
public void addToRule(Rule r){
if(!getRuleList().contains(r))
getRuleList().addElement(r);
}
public static void main(String args[]){
RuleEngine re = new RuleEngine();
Rule r = new Rule("Rule1");
re.addToRule(r);
System.out.println(re.getRuleList().contains(r));
}
}
class Rule{
public String name = "";
public Rule(String nam){
this.name=nam;
}
}
OK people have told me that this works because of the pass by reference in java. I get it. but what can i do to get a copy of that object instead of its reference?
I'm guessing getRuleList() is returning a reference to a List (or something similar). Think of it as a pointer (or more specifically, a copy of a pointer) if you're familiar with C. You're working on the same underlying instance of the object when you call getRuleList().
For proof, try: System.out.println(getRuleList() == getRuleList()); The == operator will only compare if the two references are pointing to the same object (not a deep equal like .equals). You'll see that until you call setRuleList() with a different object reference that the statement holds true.
These assumptions are of course without seeing your full code.
So, to answer your questions you have to at first know how Java passes Variables.
a Variable has a value:
int i = 1234;
Person p = new Person("Peter");
Now, the Variable i contains exactly 1234, while the Variable p contains the Memory Adress of the created Person.
so i contains 1234 and p contains the adress (let's say a4dfi3).
anyMethodYouLike(p);
System.out.println(p.getName());
public void anyMethodYouLike(Person somePerson) {
somePerson.rename("Homer");
}
so in this example, we give the Method anyMethodYouLike the Variable p... wait! we give the Method the value of the Variable (a4dfi3). The Method then calls rename on this Variable (which still has the same adress as p has, hence it modifies the same Person that p points to).
So, after the Method, the Name of the Person p points to, gets printed, which results in "Homer".
someOtherMethod(p);
System.out.println(p.getName());
public void someOtherMethod(Person somePerson) {
somePerson = new Person("Walter");
}
In THIS example we still give the adress of our Person called "Peter" to the Method. But this time, the Method creates a new Person in somePerson (therefore overriding the adress in somePerson to.. let's say 13n37s.
BUT! the Person at a4dfi3 wasn't changed! The print call still outputs "Peter" and not "Walter".
Now, let's see how this behaves with primitives:
someMethod(i);
System.out.println(i);
public void someMethod(int someInt) {
someInt++;
}
So, the Value of i (1234) gets passed to someInteger. Then someInteger gets incremented to 1235. But i is still 1234.
This is the big difference between Objects and primitives in Java.
Hope I could help,
Ferdi265
From your comments it looks like you have not completely understood what the difference is between a value and a reference in Java. Basically, objects are always passed around as references in Java.
Consider
class Test {
private List list = new ArrayList();
public List getList() {
return list;
}
}
The getList() method will return a reference to the list object. It will not return a copy of the list object. Doing something like
Test test = new Test();
String s = "ABC";
test.getList().add(s);
System.out.println(test.getList().contains(s));
Will return true since the first time getList() is called, a referece to the list is returned, on which add(s) is invoked. The second time getList() is called, it returns a reference to the same list, not a copy of it, not a new list - the same reference. Calling contains(s) will return true since it the same list onto which the object s was added.
Consider this, however.
Test test1 = new Test();
Test test2 = new Test();
String s = "ABC";
test1.add(s);
System.out.println(test2.getList().contains(s));
This will print out "false". Why? test1.getList() returns a reference to the list inside test1 and test2.getList() returns a reference to the list inside test2. Here, s was added to test1:s list, so it will not be contained inside test2:s list.
It should always print true, because you add the rule to the rule list in case it is not there. What happens is:
you tell the object to add add a rule to its rule list
the objects checks if the rule exists, and if it doesn't, adds it
So it is guaranteed to contain the rule after the code is executed.

Categories