Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Mar 2008
    Posts
    136
    Thanks
    39
    Thanked 1 Time in 1 Post

    Field of another class

    Hi all,
    I haven't got a problem, but instead a question.
    Take a look at the code below:

    Code:
    public class Server  
    {
        private Client message;
        
        public Server(Client message)
        {
         ...
    When you create a field of a type of another class, and then you use that in a parameter, what exactly are you doing?

    I understand what is achieved from writing, let's say:

    Code:
    message = new Client();
    As this would create a new object of type Client which could be used to call methods. However, in the first code I have shown you I haven't created a new object from it, but used the objects as a parameter.

    Please explain what is happening in that code, thanks

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    You will need to construct an instance of Client or at least assign a typeof Client to the given argument.
    Constructing a class is like creating a new datatype. When a method requires a typeof object: public void myMethod(Integer i) this method requires it to be provided an instanceof Integer (thats the integer wrapper class, not the primitive int value). Same goes with you're above code, the difference is that the class Server only cares that a Client is provided, it does not care how it got there. This is why you can call any public method on Client argument even without an instance. This assumes that you'll be providing a valid Client instance, so make sure you're try/catching for appropriate exceptions.
    You're code will in the long run look like so:
    Code:
    public static void main(String... argv)
    {
        Client c = new Client(?);
        Server s = new Server(c);
    }
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #3
    Regular Coder
    Join Date
    Jan 2009
    Location
    india
    Posts
    145
    Thanks
    0
    Thanked 5 Times in 5 Posts
    When you pass the object as argument to a method, your are actually passing its reference to the method. so the method can use it just like a newly constructed object, can call methods on it or do whatever it wants to. It is pass by reference and not pass by value, so it will affect original object as well.

    ----------
    SN
    Servlet central
    -----------
    Last edited by servlet; 01-20-2009 at 05:09 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •