Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 3 of 3 FirstFirst 123
Results 51 to 54 of 54

Thread: Splitting up main method / class

  1. #51
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    An example for a higher level class might be life form, Animal might be a lower class than life form, although I'm not sure that if LifeForm was being used and Animal was an extension of LifeForm, would Pig then be an extension of Animal? (Can you have 'nested' extensions?
    Yes. Look at the A, B, C, D classes example. C extends B, and B extends A, so C is-a B and it is also an A. By default, all classes extend the Object class already.

    We / The Java program will know this because we're going to use the

    if(animal instanceof Pig)

    Statement.... without this statement would it know? Or rather, this statement is just to enable us to return certain thing's based on what class / object is returned by the list....

    So at RunTime the animal is what ever sub-class was entered by the user, cow / sheep / pig... So for example say the PigClass had a method called makeBacon(), at what point could we use

    animal.makeBacon();

    I'm assuming that this is somehow wrong, because it would be a bit odd to have all the pig's, cow's and sheep to be called 'animal'.
    It really does make sense, I think that I understand how the logic work's within the examples given and on a more general level. There are still some uncertainties about details though, such as the makeBacon() example above.
    Ok, so yes, we can use the instanceof to do some Animal-specific thing, but it is more commonly used (for situations like this) to perform "casting". Casting lets us restore the real type of the object. I'll explain with code:
    Animal animal = animalList.get(i);
    if(animal instanceof Pig) { 	// Check the type of the animal
    	Pig pig = (Pig)animal; 	// Cast the animal into a Pig variable type
    	pig.makeBacon();	// Call the makeBacon() method with the pig variable
    }
    So, as you can see, we can determine the real type of the object at compile time, but we need to check the type with the instanceof operation. If we don't you will get a compiler warning (depending on your IDE), and a runtime exception will be thrown if the animal is anything other than a Pig, so it is best to check with the instanceof operation first.

    I'm a little unsure here actually with how the variable userAnimal and promptUser animal is being passed around.

    In the main method the userAnimal is created from the promptUser method - so the animal String variable from promptUser is replaced by the user defined userAnimal.... But in the FarmClass our createAnimal method has an input of String Animal - this input is the animal variable from the promptUser class, that is now the userAnimal.

    So - the animal variable still exists within the FarmClass - but it's value has been replaced by the value input by the user. This happens before the code from the createAnimal method is processed, so by the time the process get's to createAnimal the variable animal is the animal that was input by the user. We can use the animal variable in the createAnimal class because it's returned by it's method.
    Your analysis of what the program was correct up until this point. Ok, there are two concepts at work here: "variable scope" and "pass-by-value". First of all, "variable scope". When you declare a new variable within a set of curly brackets (ie: a "block of code"), that variable only exists within that block of code (as well any nested blocks of code). So the variable in the promptUser and the createAnimal() methods are not the same. When the promptUser method ends, the animal variable inside of it gets destroyed. The VALUE of the variable is returned from the method. We then set the VALUE of the userAnimal variable in the main to the VALUE returned by the promptUser method. We then send the VALUE of the userAnimal variable to the createAnimal() method. In the createAnimal() method, a brand new String animal variable is created (which will be destroyed when the createAnimal() method ends), and its value is set to the VALUE which was sent to the method. This behavior is known as "pass-by-value", meaning we are passing around the value of variables, instead of the reference to variables. Now, String is an object, and most objects are passed by reference instead of value. But String is different because of something called immutability, which just means it cannot be directly edited, so the values are passed instead of the object references. I'm not going to get into immutability right now, because it can be confusing. Just know that String are passed by value, not reference.

    So now we're in the createAnimal class, the user having specified which they'd like to create. We create a tempAnimal and assign it's value to null. This is because we've already used the variable animal in the class (as input) so need to have another variable that can be used within the createAnimal class. Although tempAnimal is of type Animal where as animal is a String - so hmm. So what is tempAnimal at the stage of

    Animal tempAnimal = null;

    It's value is null - but is it an 'animal' ? Has this in some way declared an abstract class? I know it's not with the 'new' operator, but still. So at this point is tempAnimal an Animal, and because it's abstract its value is null?
    When you declare a local variable in a method, you must set it to something. Null means it has no value and has not been initialized to anything. The tempAnimal variable has no instance associated to it. If you tried to call any of the Animal class's methods on it, you will get a NullPointerException at runtime, telling you that tempAnimal has no value. The "variable type" is still Animal, but it has no value. So if you want a local variable to have no value at the start of a method, you set it to null.

    So does Java convert them as it's putting them into the list or as it's pulling them out?
    This is the pass-by-reference that I mentioned. animal is an object (and not immutable), so when you pass the object to the animalList.add() method, you are passing the reference in memory of the initialized object itself. When you pull the object out with the get() method, you are also pulling out the reference in memory to the object. So the same reference which you put into the list at a certain index will be the one which comes out. Any changes you make to the object will affect all variables which have a reference to that object in memory. No converting ever happens, because java does not need to.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  2. #52
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    posted early... editing now!

  3. #53
    Member
    Join Date
    Dec 2013
    Posts
    51
    Thanks
    11
    Thanked 0 Times in 0 Posts

    Default Re: Splitting up main method / class

    sorry.... had my wisdom tooth removed yesterday and it's a bit controlling at the moment

    anyway!

    Yes. Look at the A, B, C, D classes example. C extends B, and B extends A, so C is-a B and it is also an A
    Of course, nice one.

    Ok, so yes, we can use the instanceof to do some Animal-specific thing, but it is more commonly used (for situations like this) to perform "casting". Casting lets us restore the real type of the object. I'll explain with code:


    Animal animal = animalList.get(i);
    if(animal instanceof Pig) { 	// Check the type of the animal
    	Pig pig = (Pig)animal; 	// Cast the animal into a Pig variable type
    	pig.makeBacon();	// Call the makeBacon() method with the pig variable
    }
    Oh right, - but in this case it's used instanceof to run code as soon as the relevant animal is created. So as soon as a Pig is made the makeBacon() method is used instead of leaving it to the user to decide whether or not to 'make bacon' after

    I've encountered bit's of casting, like when a floating point is cast to an int and the decimals are truncated.

    Casting lets us restore the real type of the object
    Do you mean it lets us change from the animal to a pig?

    So, as you can see, we can determine the real type of the object at compile time, but we need to check the type with the instanceof operation
    So this has confused me - how can we determine the type of object at compile time when the user hasn't even given input? Or do you mean we determine that it's an animal (or type of) at compile time?

    In the createAnimal() method, a brand new String animal variable is created
    Right, I'm pretty much following along with that paragraph and the passing of the values. But I wanted to check this - so when you say that a brand new String is created for the purposes of the method - you're referring to the String animal part from the parentheses?

    public void createAnimal(String animal)

    And the String here is given the value provided by the user. This String animal could say String XYZ, it wouldn't change the program, but for the purposes of making the code 'make sense' it's called animal. As an animal name is input there.

    When we say the value of String, the VALUE of the userInput String is what they entered... So if they entered "Pig", the VALUE of the String unserInput would be "Pig"... Is that right? But if there was a variable int i = 20; then wouldn't it's VALUE be 20? (If I'm getting into immutability territory, or just something for another time just say!)

    animal is an object (and not immutable)
    An abstract class is still an object then... the object that we pass to animalList.add() is tempAnimal, which IS an animal... So I guess that's just like passing animal.


    I'm going to leave it there before I start making circles...


    Not sure what the actual program's meant to be doing at the moment...

    cheers though!

  4. #54
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Splitting up main method / class

    had my wisdom tooth removed yesterday
    Not fun. I had mine taken out 8 months ago. Trust me, you'll be glad you got it done if you aren't already glad.

    Oh right, - but in this case it's used instanceof to run code as soon as the relevant animal is created.
    No animal is created. The existing animal in memory now has two variables referencing to it: animal and pig. Both of these variables reference the same pig. If you made a change to the Pig object with the animal variable, the pig variable would change too, ect.

    So this has confused me - how can we determine the type of object at compile time when the user hasn't even given input? Or do you mean we determine that it's an animal (or type of) at compile time?
    By that statement, I meant we are determining that if animal is of the Pig type, then we want to do certain things with it as a Pig (instead of a generic animal). Casting is what lets us create a variable with a less ambigious type.

    But I wanted to check this - so when you say that a brand new String is created for the purposes of the method - you're referring to the String animal part from the parentheses? ... And the String here is given the value provided by the user. This String animal could say String XYZ, it wouldn't change the program, but for the purposes of making the code 'make sense' it's called animal. As an animal name is input there...When we say the value of String, the VALUE of the userInput String is what they entered... So if they entered "Pig", the VALUE of the String unserInput would be "Pig"... Is that right? But if there was a variable int i = 20; then wouldn't it's VALUE be 20? ... An abstract class is still an object then... the object that we pass to animalList.add() is tempAnimal, which IS an animal... So I guess that's just like passing animal.
    Yes to all of that.

    Not sure what the actual program's meant to be doing at the moment...
    Um, I think we were creating the getPigCount(), getSheepCount(), and getCowCount() methods.
    So, now that you seem to understand the discussion, each of those methods should loop through the animalList. For each index in the animalList, we want to check the type of the animal (using instanceof) and if the method should include that animal in the count, we increment the count. So in the getPigCount() method, we loop through the animalList, check if the animal is an instanceof Pig, and if it is, we increment our count. If it isn't, we just ignore the animal. At the end of the method, we return our count variable.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Page 3 of 3 FirstFirst 123

Similar Threads

  1. Replies: 2
    Last Post: November 18th, 2012, 02:09 PM
  2. create a test class (main method) to start(run) the class in Java
    By curious725 in forum Java Theory & Questions
    Replies: 5
    Last Post: August 1st, 2012, 03:21 AM
  3. Main method/ class problem. I can't run any script!
    By BokBok in forum What's Wrong With My Code?
    Replies: 3
    Last Post: June 28th, 2012, 05:14 PM
  4. Paint program adding classes to main method class
    By Maxfmc in forum What's Wrong With My Code?
    Replies: 0
    Last Post: April 15th, 2011, 07:01 PM
  5. Creating a scaleUp main method in a new class
    By Brainz in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 16th, 2010, 08:58 AM