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.

Results 1 to 10 of 10

Thread: 'new' instantiating command ??

  1. #1
    Junior Member
    Join Date
    Jul 2014
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default 'new' instantiating command ??

    New to this forum and java programming. Quick question about the new command when instantiating a new object.

    If you have...

    class_name object_name = new class_name(arg list)

    So on the left side of the equals sign we are only making a declaration that we will be (but not yet) creating a object of the data type class_name. On the right side of the equals sign we use the new command to actually instantiate it and put it into a physical memory location in RAM. After the new declaration, the second time we use the class_name, is this...

    1) Just a call to the constructor of class_name
    2) Something more.

    I am getting stuck with statements like this (specifically perataining to ABSTRACT classes since they cannot be instantiated):

    class_name object_name = new DIFFERENTclass_name(arg list)

    What is going on in a situation like this when we use a DIFFERENTclass_name. Is this also an instantiation too?



    Thanks
    Adam


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

    Default Re: 'new' instantiating command ??

    On the left side, you are creating a variable, named object_name, with the type class_name. On the right side, you are initializing a new class_name object. This is an important distinction.
    The right side can exist without the left side, but it will be garbage collected not long after (in most cases), since there would be no references to the allocated object.
    When we talk about inheritance (such as abstract classes), it is important to understand that the type of a variable does not necessarily guarantee the type of the object initialized to the variable. All that is required is that the initialized object is of the same type, or a subtype of, the variable type. Setting an object to a supertype variable does not, in any way, change the way the object is initialized or stored in memory. Instead, it limits your ability to access features of the subtype at compile time.
    Consider that ALL classes can be initialized to a variable of type Object, but if you try to use that variable, you will find that you only have access to the methods declared in the Object API (Object (Java Platform SE 7 )).

    Tell me how much of that made sense, and how much didn't. I'm pretty sure you'll want more detail in certain areas.
    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/

  3. The Following 2 Users Say Thank You to aussiemcgr For This Useful Post:

    GregBrannon (July 29th, 2014), turboman1 (July 29th, 2014)

  4. #3
    Junior Member
    Join Date
    Jul 2014
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: 'new' instantiating command ??

    Quote Originally Posted by aussiemcgr View Post
    On the left side, you are creating a variable, named object_name, with the type class_name.
    I understand this part. It is just like creating a variable of type integer ("int a"). "int a" does not actually create any memory yet, bc it is just a declaration of a variable.

    Quote Originally Posted by aussiemcgr View Post
    On the right side, you are initializing a new class_name object.
    This is the part that is confusing me. Following from the "int a" example, you would only be able to initialize "a" with an integer, thus you could not use " a='A' " bc that is of a different data type. So why is it you can declare an object of a certain data type (class_name object_name = ...), but yet on the right side you can instantiate it with another data type (only a derived class though)? Seems like you are declaring one data type but then initializing it to another data type.

    Quote Originally Posted by aussiemcgr View Post
    The right side can exist without the left side, but it will be garbage collected not long after (in most cases), since there would be no references to the allocated object.
    Did not know this, is there ever a reason to have such a statement in the code?

    Quote Originally Posted by aussiemcgr View Post
    When we talk about inheritance (such as abstract classes), it is important to understand that the type of a variable does not necessarily guarantee the type of the object initialized to the variable. All that is required is that the initialized object is of the same type, or a subtype of, the variable type.
    ^^^^This is basically my question, please explain this more^^^^^

    Quote Originally Posted by aussiemcgr View Post
    Setting an object to a supertype variable does not, in any way, change the way the object is initialized or stored in memory. Instead, it limits your ability to access features of the subtype at compile time.
    This I understand. If you set an object to a base class you cannot access any of the derived class methods or fields, but if you have a derived class you can access (within restrictions of private, public, protected) the base class.

    Quote Originally Posted by aussiemcgr View Post
    Consider that ALL classes can be initialized to a variable of type Object, but if you try to use that variable, you will find that you only have access to the methods declared in the Object API (Object (Java Platform SE 7 )).
    This I have read but never used, just another thing to get too eventually.

    Thank you for your help

  5. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. The Following User Says Thank You to KevinWorkman For This Useful Post:

    turboman1 (July 29th, 2014)

  7. #5
    Junior Member
    Join Date
    Jul 2014
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: 'new' instantiating command ??

    Kevin, in the recommended reading you posted I have a question.

    Casting shows the use of an object of one type in place of another type, among the objects permitted by inheritance and implementations. For example, if we write

    Object obj = new MountainBike();

    then obj is both an Object and a MountainBike (until such time as obj is assigned another object that is not a MountainBike). This is called implicit casting.
    1)How is this any different than writing....

    MountainBike obj = new MountainBike()

    Since MountainBike() is a derived class and has access to all the non-private members of obj?
    OR
    Is this saying that obj is of data-type MountainBike BUT IS restricted to the use of members ONLY of class Object?

    2) They go on to say that...
    If, on the other hand, we write

    MountainBike myBike = obj;

    we would get a compile-time error because obj is not known to the compiler to be a MountainBike
    Just after they said obj IS BOTH a Object and MountainBike, now they say the compiler does not know that obj is a MountainBike. That statement confuses me even more.

    Thanks
    Adam

  8. #6
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: 'new' instantiating command ??

    Because sometimes you dont want a mountain bike. Sometimes you want to work with something simpler.
    The example they give here is a bad example in my opinion because its too far away from any real use.

    A better example is always the different kinds of collections. Imagine we want to have a certain number of Strings saved in some kind of collection. The only thing we are going to do with these is to iterate over them and print them one by one.
    Our code might look like this:
    	private Iterable<String> strings = Arrays.asList(new String[] {"Hello", "World", "how", "are", "you"});
     
    	public void printAll(Iterable<String> toBePrinted) {
    		for (String str : toBePrinted) {
    			System.out.println(str);
    		}
    	}

    You see, we could also write the following:
    	private List<String> strings = Arrays.asList(new String[] {"Hello", "World", "how", "are", "you"});
     
    	public void printAll(List<String> toBePrinted) {
    		for (String str : toBePrinted) {
    			System.out.println(str);
    		}
    	}
    Because we already know that we store our strings as a list.
    But imagine that sometime in the future we choose to change the way we store strings.
    What happens if we suddenly dont want to have a list anymore, but instead, perhaps a Set of Strings:
    	private Set<String> strings = new HashSet<>(Arrays.asList(new String[] {"Hello", "World", "how", "are", "you"}));
     
    	public void printAll(List<String> toBePrinted) {
    		for (String str : toBePrinted) {
    			System.out.println(str);
    		}
    	}
    Now we also need to change our "printAll" method. It doesnt work anymore because its still expecting a List.

    But if we kept it to use an Iterable instead we would not have this problem.


    The idea is to always keep all your references as simple as possible. We dont care whether we store our Strings as a List or as a Set if all we do is iterate over them.
    So we use Iterable instead of the more fine grained classes because Iterable is all we need.

  9. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: 'new' instantiating command ??

    Quote Originally Posted by turboman1 View Post
    Object obj = new MountainBike();
    1)How is this any different than writing....
    MountainBike obj = new MountainBike()
    You've got a variable named obj. That variable can point at anything that is an Object. The example code points it at an instance of MountainBike. You could also point it at a String or an ArrayList or any other Object.

    Think about it this way: What if we had another class just named Bike. We might extend that class by writing a MountainBike class that extends Bike as well as a Motorcycle class that extends Bike. Both MountainBike and Motorcycle **are** Bikes, since they extend Bike.

    Now say you have a Bike variable named myBike. That variable can point to instances of MountainBike or instances of Motorcycle. This is particularly useful when you get to arrays and ArrayLists, since you can group similar Objects together.

    Quote Originally Posted by turboman1 View Post
    Just after they said obj IS BOTH a Object and MountainBike, now they say the compiler does not know that obj is a MountainBike. That statement confuses me even more.
    Another example:

    Say you have an Animal class, and you have 3 classes that extend it: Mammal, Bird, and Reptile. All Mammals are Animals, but not all Animals are Mammals, since some are Birds or Reptiles. That's why I can do this:

    Animal myAnimal = new Mammal();

    All Java knows at this point is that myAnimal is an Animal. It doesn't know that that Animal is a Mammal, because you might do something like this:

    Animal myAnimal;
     
    if(Math.random() < .5){
       myAnimal = new Mammal();
    }
    else{
       myAnimal = new Bird();
    }
     
    //what type is myAnimal? You can't know until runtime!

    So now if you try to do this, the compiler will give you an error:

    Mammal myMammal = myAnimal;

    You can tell Java that you know what type an Object is by *casting*, which basically says "don't worry Java, I know what type this object is, trust me":

    Mammal myMammal = (Mammal) myAnimal;

    However, if you're wrong and myAnimal is a Bird or a Reptile, then you'll get a runtime error!
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

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

    Default Re: 'new' instantiating command ??

    Consider the three example classes below, which I will use to answer your question:
    public class Value {
    	private int value;
     
    	public Value(int val) {
    		value = val;
    	}
     
    	public int getInt() {
    		return value;
    	}
    }
     
    public class ExampleA {
    	private Value value;
     
    	public ExampleA(Value val) {
    		value = val;
    	}
     
    	public Value getValue() {
    		return value;
    	}
     
    	@Override // All objects have a toString() method
    	public String toString() {
    		return "This is an ExampleA object, with value: "+getValue().getInt();
    	}
    }
     
    public class ExampleB extends ExampleA {
    	public ExampleB(Value val) {
    		super(val);
    	}
     
    	@Override
    	public String toString() {
    		return "This is an ExampleB object, with value: "+getValue().getInt();
    	}
    }

    This is the part that is confusing me. Following from the "int a" example, you would only be able to initialize "a" with an integer, thus you could not use " a='A' " bc that is of a different data type. So why is it you can declare an object of a certain data type (class_name object_name = ...), but yet on the right side you can instantiate it with another data type (only a derived class though)? Seems like you are declaring one data type but then initializing it to another data type.
    Using int is a bad example, since int is a primitive, and primitives do not have inheritance. Let's depict this with Objects instead.
    Ok, so let me give you a few lines of code:
    Value value1 = new Value(3);
    ExampleA var1 = new ExampleA(value1); // Set a new ExampleA object to the var1 variable, with type: ExampleA
    Value value2 = new Value(5);
    ExampleB var2 = new ExampleB(value2); // Set a new ExampleB object to the var2 variable, with type: ExampleB
    Value value3 = new Value(7);
    ExampleA var3 = new ExampleB(value3); // Set a new ExampleB object to the var3 variable, with type: ExampleA
    System.out.println(var1.toString());
    System.out.println(var2.toString());
    System.out.println(var3.toString());
    So all of that code above would be allowed. The output would be:
    This is an ExampleA object, with value: 3
    This is an ExampleB object, with value: 5
    This is an ExampleB object, with value: 7
    Now, why does var3 (whose type is ExampleA) use the ExampleB's toString() method? Here you have to understand the difference between compile time and run time. At compile time (the time before and after you compile code), var3 is considered to be a ExampleA object, so when you write the code, you only have access to the ExampleA methods. At runtime (the time where the code is actually being executed), however, the virtual machine knows that, despite var3 having the type ExampleA, the instance assigned to var3 is ACTUALLY an ExampleB object, so it uses the ExampleB methods.
    When is this behavior useful? Let's say you had an array where you wanted to hold both ExampleA and ExampleB objects. How would you declare that? Well, since ExampleB extends ExampleA, we can create an array of type ExampleA and add both ExampleA and ExampleB objects to it. The catch to this is that when we pull an object out of an array, we will not know if it is "really" an ExampleA object or an ExampleB object. But, that is not much of a problem for us, since the true type of the object will be known at runtime.
    ExampleA[] exampleArray = new ExampleA[3];
    exampleArray[0] = var1;
    exampleArray[1] = var2;
    exampleArray[2] = var3;
    for(int i=0;i<exampleArray.length;i++) {
    	ExampleA temp = exampleArray[i];
    	System.out.println(temp.toString());
    }
    This will also output:
    This is an ExampleA object, with value: 3
    This is an ExampleB object, with value: 5
    This is an ExampleB object, with value: 7

    Did not know this, is there ever a reason to have such a statement in the code?
    Let's say we didn't want to waste a variable on a Value object when we create ExampleA objects. We can do this by creating a new Value object inside of the ExampleA constructor:
    ExampleA var4 = new ExampleA(new Value(10));
    Or, let's say we just wanted to get the output print of an ExampleB with a value of 2, without setting a variable:
    System.out.println(new ExampleB(new Value(2));
    This would output the following line, and then the newly created ExampleB object would be immediately destroyed:
    This is an ExampleB object, with value: 2
    These are two examples of when you could do this, but they aren't exactly the best examples possible. You will see this behavior in many situations in your future.

    This I have read but never used, just another thing to get too eventually.
    All classes are automatically inherited from the Object class. Therefore, any object you create can be assigned to a variable with type Object. Consider the following code:
    Object var5 = new ExampleB(new Value(1));
    System.out.println(var5.toString());
    This is allowed, since the toString() method comes from the Object class. This code would output:
    This is an ExampleB object, with value: 7
    However, the following code would produce a compile time error:
    System.out.println("Value: "+var5.getValue()); // Error at var5.getValue()
    This would create an error because the var5 variable does NOT have access to the ExampleB's getValue() method at compile time. It is not known that var5 is really an ExampleB object at compile time. At best, we know that var5 is of type Object, so var5 only has access to methods declared in the Object class.
    Last edited by aussiemcgr; July 29th, 2014 at 01:43 PM.
    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/

  11. #9
    Junior Member
    Join Date
    Jul 2014
    Posts
    4
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: 'new' instantiating command ??

    Quote Originally Posted by KevinWorkman View Post
    Another example:

    Say you have an Animal class, and you have 3 classes that extend it: Mammal, Bird, and Reptile. All Mammals are Animals, but not all Animals are Mammals, since some are Birds or Reptiles. That's why I can do this:

    Animal myAnimal = new Mammal();

    All Java knows at this point is that myAnimal is an Animal Are you talking about the Animal myAnimal = new Mammal() ? If so I thought that in this statement you are telling the compiler that myAnimal is of data type Mammal but it ONLY has access to the members of Animal class. It doesn't know that that Animal is a Mammal, because you might do something like this:

    Animal myAnimal;
     
    if(Math.random() < .5){
       myAnimal = new Mammal();
    }
    else{
       myAnimal = new Bird();
    }
     
    //what type is myAnimal? You can't know until runtime!

    Kevin I think I am starting to get this. So let me ask another question if you have two statements like this...

    Animal myAnimal = new Mammal()
     
    // Versus
     
    Animal myAnimal = new Animal();

    The differences between these two statements is...
    The first statement declares myAnimal as data type Mammal, but it ONLY has access to Animal class members?

  12. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: 'new' instantiating command ??

    Quote Originally Posted by turboman1 View Post
    Are you talking about the Animal myAnimal = new Mammal() ? If so I thought that in this statement you are telling the compiler that myAnimal is of data type Mammal but it ONLY has access to the members of Animal class.
    I'm not sure what you mean by "has access to" in this context. Since your myAnimal variable is of type Animal, yes, you'll only be able to call functions that exist in the Animal class. However, if you **override** one of those methods in the Mammal class, then the method from the Mammal class will be called.

    Quote Originally Posted by turboman1 View Post
    Animal myAnimal = new Mammal()
    // Versus
    Animal myAnimal = new Animal();

    The differences between these two statements is...
    The first statement declares myAnimal as data type Mammal, but it ONLY has access to Animal class members?
    Again, "has access to" doesn't make a lot of sense to me in this context. The first statement declares myAnimal as type Animal, but it initializes it to a Mammal instance. You still "have access to" any methods in Mammal that **override** methods in Animal. The second statement declares the variable as the base type.

    Let's expand the example. Let's say we have a base Animal class:

    class Animal{
       public void eat(){
          System.out.println("The animal eats its food.");
       }
     
       public void talk(){
          System.out.println("The animal talks.");
       }
    }

    And we have two classes, Cat and Dog, that both extend it:

    class Cat extends Animal{
       public void eat(){
          System.out.println("The CAT eats FISH.");
       }
     
       public void talk(){
          System.out.println("The cat MEOWS.");
       }
    }
     
    class Dog extends Animal{
       public void eat(){
          System.out.println("The DOG eats BONES.");
       }
     
       public void talk(){
          System.out.println("The dog BARKS.");
       }
    }

    Now, we can declare three Animal variables and initialize them to intances of each of the classes:

    Animal animal = new Animal();
    Animal cat = new Cat();
    Animal dog = new Dog();

    And we can create a function that takes an Animal as an argument and tells that animal to talk and eat:

    public void talkAndEat(Animal a){
       a.talk();
       a.eat();
    }

    Now we can pass each instance (Animal, Cat, and Dog) into that function:

    Animal animal = new Animal();
    Animal cat = new Cat();
    Animal dog = new Dog();
     
    talkAndEat(animal);
    talkAndEat(cat);
    talkAndEat(dog);

    What do you think that code would print out? I suggest writing a little example program to test your answer.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  13. The Following User Says Thank You to KevinWorkman For This Useful Post:

    GregBrannon (July 30th, 2014)

Similar Threads

  1. why the command prompt does not recognize java as a command?
    By bihlas in forum Java Theory & Questions
    Replies: 1
    Last Post: July 22nd, 2014, 09:50 AM
  2. instantiating static methods
    By nickdesigner in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 23rd, 2013, 08:47 PM
  3. [SOLVED] problem with instantiating object
    By Goldfinch in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 1st, 2012, 10:28 PM
  4. instantiating a object
    By Neo in forum Object Oriented Programming
    Replies: 7
    Last Post: April 19th, 2011, 02:16 AM
  5. Need help with instantiating a class
    By suxen in forum What's Wrong With My Code?
    Replies: 4
    Last Post: March 30th, 2011, 03:35 PM