Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: [1] 2

Author Topic: A question regarding learning Java  (Read 6166 times)

AllThingsLive

  • Bay Watcher
  • Damn, I'm a sexy bitch!
    • View Profile
A question regarding learning Java
« on: September 10, 2011, 10:34:04 pm »

I'm reading the book Java Concepts for Java editions 5 and 6, by Cay Horstmann, it's a big ol' 1,100 page textbook on Java. I'm about 100 pages in, and I'm having some difficulties. (Learning objects was a big problem for me earlier as I'm sure some of you guys know) In the book, as part of review for chapter 2 it says :
"Exercise R2.7 : Give Java code to construct the following objects:
a. A rectangle with center (100, 100) and all side lengths equal to 50
b. A string “Hello, Dave!”
Create objects, not object variables.

Exercise R2.8. Repeat Exercise R2.7, but now define object variables that
are initialized with the required objects."

I read the chapter, but I don't quite understand these 2 things.
As far as I can tell, this is how you're supposed to do it :
Code: [Select]
import java.awt.Rectangle;

public class Exercises {
public static void main(String[] args){
/*
   Exercise R2.7
   Here I have no clue how to make just a rectangle object,
   I only know how to make references.
*/
System.out.println("Hello, Dave!");

/*
   Exercise R2.8
   This one seems easy enough. As far as I know,
   I made a rectangle object here, with apple as the object variable.
*/
Rectangle apple = new Rectangle(75,75,50,50);
String helloThere = "Hello, Dave!";
}
}
I'm really trying hard to learn Java, but I'm not too good with all these new concepts, especially not by reading a very dry textbook. (I learn better by hearing and seeing the things I'm learning/doing, but I do want to learn to program some day, I've always loved computers)
So any help you can provide would be very much appreciated.
By the way, this is my first programming language, so please respond in a somewhat newbie friendly way.
Logged
If you haven't already, you MUST listen to the Joe Rogan Experience : http://itunes.apple.com/us/podcast/the-joe-rogan-experience/id360084272

Stargrasper

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #1 on: September 11, 2011, 12:55:51 am »

I feel like that problem set could have been more clearly written.  Anyway...I'm pretty sure this is what it's asking for.  Let me know if you have any problems.  And don't be afraid to ask for help.  Mind that this forum may not be the best place to ask, there are a surprising number of programmers here...

Code: [Select]
package com.bay12games.stargrasper.excerses;

import java.awt.Rectangle;

public class Exercises {

public Exercises() {
// Exercise R2.7

// This creates a new Rectangle object with the desired attributes...and
// then promptly drops it into the void.
new Rectangle(75, 75, 50, 50);

// This creates a new String object with the desired text...and again
// just drops it into the void.
new String("Hello, Dave!");

// Excercise R2.8

// This creates a new Rectangle object with the desired attributes, but
// this time saves it to a variable for future use.
Rectangle foo = new Rectangle(75, 75, 50, 50);

// This creates a new String object with the desired text; and similarly
// saves it to a variable.
String bar = new String("Hello, Dave!");
}

public static void main(String[] args) {
// Because I absolutely HATE being in static methods.
// Completely unnecessary in this case.
new Exercises();
}

}

Logged

AllThingsLive

  • Bay Watcher
  • Damn, I'm a sexy bitch!
    • View Profile
Re: A question regarding learning Java
« Reply #2 on: September 11, 2011, 12:02:09 pm »

Okay, I get it now, but one quick question;
Is
Code: [Select]
System.out.println("Whatever");
Different from
Code: [Select]
String whatever = "Whatever";
Or
Code: [Select]
new String("Whatever");
?
Logged
If you haven't already, you MUST listen to the Joe Rogan Experience : http://itunes.apple.com/us/podcast/the-joe-rogan-experience/id360084272

eerr

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #3 on: September 11, 2011, 12:35:29 pm »

All you need is

"Whatever";
Logged

Rafal99

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #4 on: September 11, 2011, 01:57:10 pm »

Okay, I get it now, but one quick question;
Is
Code: [Select]
System.out.println("Whatever");
Different from
Code: [Select]
String whatever = "Whatever";
Or
Code: [Select]
new String("Whatever");
?

First one prints "Whatever" to the console.
Second one creates a String variable named "whatever" with a value "Whatever".
Third one created a String variable too but it doesn't have a name so it can't be accessed later.

If you typed:
Code: [Select]
String whatever = new String("Whatever");
it would be equivalent to the second one.
Logged
The spinning Tantrum Spiral strikes The Fortress in the meeting hall!
It explodes in gore!
The Fortress has been struck down.

Stargrasper

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #5 on: September 11, 2011, 06:18:21 pm »

Java is one of those languages that does a lot of things for you to make your life "easier".  For example, String is an object.  To instantiate all objects, you must use the new command.  This functions as a memory allocation (another thing Java does for you).  String is such a commonly used object, however, that Java actually pretends it's a primitive during instantiation.  This means that Java actually allows you to create strings without newing them.
Code: [Select]
// These are functionally identical.
// This one uses the function that pretends String objects are primitives during instantiation.
String s1 = "foo";
// This is a more "proper" instantiation of a String object.
// Note that nobody does this outside of a purely academic situation...like this one, so that you know what's really happening.
String s2 = new String("foo");

You'll see this in a number of places.
Code: [Select]
// This actually creates a new String object for you and prints it to stdout, usually a console or log file.
System.out.println("foo");
// It should be more appropriately written as...
System.out.println(new String("foo"));
// Of course, nobody does this.
// While on the subject of System.out.println(), it will call .toString() for you.
Rectangle r = new Rectangle();
System.out.println(r);
// Will actually call...
System.out.println(f.toString());

While you can new all the Objects you want (and have to new any Object to instantiate it), it doesn't do you much good if you don't assign a pointer (a variable) to them.
Code: [Select]
// This will get instantiated...but you won't have any way to access it.
// Sooner or later (hopefully) Java will notice that it's unreachable and garbage collect it.
new String("foo");
// You need something to point to it if you want to be able to use it after instantiation.
String s3 = new String("foo");
// Or maybe...
String[] s4 = new String[10];
s4[0] = new String("foo");
// Or even...
List<String> s5 = new ArrayList<String>();
s.add(new String("foo"));
// Or use one of the rather large variety of datastructers available to you.
// It doesn't matter HOW you point to an object so long as you do.

Okay, I was trying to be thorough yet understandable.  Did all of that make sense to you?  It's reasonably technical, but I feel that you would understand the language (and find it more effective to learn) if you understood some of the nuts and bolts.
Logged

AllThingsLive

  • Bay Watcher
  • Damn, I'm a sexy bitch!
    • View Profile
Re: A question regarding learning Java
« Reply #6 on: September 11, 2011, 07:39:33 pm »

Awesome, that complete and perfect sense, thank you Star :)
Logged
If you haven't already, you MUST listen to the Joe Rogan Experience : http://itunes.apple.com/us/podcast/the-joe-rogan-experience/id360084272

AllThingsLive

  • Bay Watcher
  • Damn, I'm a sexy bitch!
    • View Profile
Re: A question regarding learning Java
« Reply #7 on: September 11, 2011, 10:36:37 pm »

Actually, while I'm at it, there was another part I didn't understand. In chapter 2, there was a little section on simple GUI, but I couldn't quite understand the stuff the author was trying to explain. This part of the chapter is optional, so I was going to pass over it and come back to it later on when I understood what the stuff meant, but I've got you guys! You guys seem to be able to explain things well to me, so here's a little test for your teaching skills; you must this ^ this idiot about the following code :
(By the way, these 2 classes are meant to make a jComponent with 2 rectangles in it.)
Code: [Select]
ch02/rectangles/RectangleComponent.java
1 import java.awt.Graphics;
2 import java.awt.Graphics2D;
3 import java.awt.Rectangle;
4 import javax.swing.JComponent;
5
6 /**
7 A component that draws two rectangles.
8 */
9 public class RectangleComponent extends
JComponent
10 {
11 public void paintComponent(Graphics g)
12 {
13 // RecoverGraphics2D
14 Graphics2D g2 = (Graphics2D) g;
15
16 // Construct a rectangle and draw it
17 Rectangle box = new Rectangle(5, 10,
20, 30);
18 g2.draw(box);
19
20 // Move rectangle 15 units to the right and 25 units
down
21 box.translate(15, 25);
22
23 // Draw moved rectangle
24 g2.draw(box);
25 }
26 }

Code: [Select]
1 import javax.swing.JFrame;
2
3 public class RectangleViewer
4 {
5 public static void main(String[] args)
6 {
7 JFrame frame = new JFrame();
8 frame.setSize(300, 400);
9 frame.setTitle(“Two rectangles”);
10 frame.setDefaultCloseOperation(JFrame.EXIT
11
12 RectangleComponent component = new
RectangleComponent();
13 frame.add(component);
14
15 frame.setVisible(true);
16 }
17 }
I understand pretty much everything in the second class, but the first one is giving me some trouble. I understand the imports and the construction of the "box", but that's pretty much it.
The author said this in order to explain the first bit, but I don't get it, what exactly is a cast? :
Quote
"However, the Graphics class is primitive. When programmers clamored for a more
object-oriented approach for drawing graphics, the designers of Java created the
Graphics2D class, which extends the Graphics class. Whenever the Swing toolkit
calls the paintComponent method, it actually passes a parameter of type
Graphics2D. Programs with simple graphics do not need this feature. Because we
want to use the more sophisticated methods to draw two-dimensional graphics objects,
we need to recover the Graphics2D. This is accomplished by using a cast:
The Graphics2D class has methods to draw shape objects.
Use a cast to recover the Graphics2D object from the Graphics parameter of
the paintComponent method."
I mainly just need help with the intricacies of the first class, I think.
Thank you guys again for all your help, and I'm sorry I have to keep asking for help, but I find this stuff really tough to learn.
Logged
If you haven't already, you MUST listen to the Joe Rogan Experience : http://itunes.apple.com/us/podcast/the-joe-rogan-experience/id360084272

Stargrasper

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #8 on: September 11, 2011, 11:37:02 pm »

The example code is pretty straight forward.  I'll explain it in detail in a little bit.  First, is casting the only thing you don't understand?

Casting is basically an explicit instruction to the compiler to automagically transform something into something else.  You do this by putting in parenthesis what you want to transform it into in from of the thing.  A common cast example...
Code: [Select]
// This is common to avoid integer division, a problem you WILL have at some point.
// Cast the int 1 into the double 1.0.
double foo = (double) 1 / 2;

// The reverse works too, if you don't mind losing data.
// Casting from a double to int arbitrarily drops the decimal.
// Meaning that this becomes 2.
int bar = (int) 2.7;

You can also cast between Objects.
Code: [Select]
// Because Rectangle inherits from Object, you can cast it back to an Object.
// The cool thing is that while it can only be treated as a Object, the system will
// remember that it's really a Rectangle, and will call appropriate overridden methods.
Rectangle r1 = new Rectangle();
Object o = (Object) r;

// And naturally, you can cast back up again.
Rectangle r2 = (Rectangle) o;
// Note that if you try to cast an Object to a Rectangle and it wasn't a Rectangle to begin
// with, it'll probably crash the program with a ClassCastException.

Now feels like a great time for a mini-lesson on inheritance.  Basically, you have Object.  Everything that isn't a primitive is an Object and specifically, Object is the cosmic superclass in Java.  All objects must inherit from Object.  If you write your own objects and don't tell it that it's inheriting from something, Java automatically assumes it inherits from Object.  This is what the extends keyword does.  It tells Java what this object inherits from.  Inheritance basically means that the object is a specialized form of whatever it's parent class is and probably has greater capability.

Graphics is an object used to allow data to be drawn onto a component.  Graphics2D inherits from Graphics and serves as a specialized form of it that allows for additional functionality.

So, the paintComponent(Graphics g) method takes in a Graphics object.  Well, it seems that it's not a Graphics object but a Graphics2D object that we're just kind of pretending is a Graphics object for simplicity.  My guess is that it gets cast from Graphics2D to Graphics internally somewhere.  The important point is, however, that since it really is a Graphics2D object, we can just cast it back.

Here's my commented version of the first example you said you didn't understand.  Since you said you understood the second, I won't bother commenting it unless you have further questions.  Just realize that the second is using the class defined in the first.
Code: [Select]
// Various necessary imports.  Ask if these confuse you.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/**
A component that draws two rectangles.
*/
public class RectangleComponent extends JComponent {
// This is the method that actually describes how to draw stuff to the screen.
public void paintComponent(Graphics g) {
// RecoverGraphics2D
// More specifically, we already told you it's really a Graphics2D object
// pretending to be a Graphics object.  Lets see it for what it really is.
// This is a simple cast.
Graphics2D g2 = (Graphics2D) g;

// Construct a rectangle and draw it
// You ought to already understand object instantiation.  As always
// ask if you have questions.
Rectangle box = new Rectangle(5, 10, 20, 30);
// The draw(Shape) method comes from Graphics2D and I don't believe
// it exists in Graphics.  This is why we had to do that cast
// in the first place.
// The draw(Shape) method paints the outline of the Shape passed
// as a parameter.  See the Java API for more detail.
g2.draw(box);

// Move rectangle 15 units to the right and 25 units down
// The translate(int, int) method in Rectangle lets you shift the x, y
// to the right and down along the respective axes.  Pass negative numbers
// if you want to move left or up.
box.translate(15, 25);

// Draw moved rectangle
// I already explained the draw(Shape) method in a fair amount of detail above.
g2.draw(box);
}
}

I'd just like to point out that I think extending JComponent isn't worth it.  Extend JPanel (which itself extends JComponent), override paintComponent(Graphics) and you can do everything you need to from there.  Then you just need to add your custom JPanel to a JFrame and it's already on screen for you.  At least, this is how I usually accomplish getting crap on screen.

As always, if there's anything confusing about any of this, just ask and I'll clarify any of it.
Logged

AllThingsLive

  • Bay Watcher
  • Damn, I'm a sexy bitch!
    • View Profile
Re: A question regarding learning Java
« Reply #9 on: September 14, 2011, 12:13:51 am »

Wow, that cleared a lot up for me. I'm sorry for being an idiot, but I still have a couple questions (Which you seem all so enthusiastic to answer, which is really cool ;D)
So, casting, I think I need just a bit more clarification on it. I tried :
Code: [Select]
public class TestClass {
public static void main(String[] args){
//By the way, what does all this crap above mean when making a method?
//Creating the integer "apple"
int apple = 7;
//Supposedly converting it into a double, but Eclipse just says that
//there is an error on "apple" and the "double" in the parentheses.
double apple = (double);
}
}
So I think I understand the idea of casting ( At least with numbers), but I'm having problems with the technicalities.
Also,
Code: [Select]
// Because Rectangle inherits from Object, you can cast it back to an Object.
// The cool thing is that while it can only be treated as a Object, the system will
// remember that it's really a Rectangle, and will call appropriate overridden methods.
Rectangle r1 = new Rectangle();
Object o = (Object) r;

// And naturally, you can cast back up again.
Rectangle r2 = (Rectangle) o;
// Note that if you try to cast an Object to a Rectangle and it wasn't a Rectangle to begin
// with, it'll probably crash the program with a ClassCastException.
When you reference "Object" do you actually mean that there is a class called "Object" or is this just a conceptual thing?
Or does "Object" in your post mean "any type of object"?
Also, can I get some more clarification on :
Code: [Select]
public void paintComponent(Graphics g) {?
As far as I can tell, JComponent was imported, and we're rewriting paintComponent. Then I don't get what's going on with "(Graphics g)".
And then what's going on with "Graphics2D g2 = (Graphics2D) g;"? So, are casts organized as
"ObjectToBeChangedInto ObjectToBeChanged = (ObjectToBeChangedInto) NewNameToBeStoredAs;"?
You explain the concepts very well, but the tiny things are getting me.
I'm sorry for being so difficult.
Logged
If you haven't already, you MUST listen to the Joe Rogan Experience : http://itunes.apple.com/us/podcast/the-joe-rogan-experience/id360084272

Stargrasper

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #10 on: September 14, 2011, 01:37:37 am »

If you're the worst student I ever tutor (and you're already not), I'll be a very happy person.

So you seem to understand the concept of casting and just don't understand it's use.  Let's do something about that.
Code: [Select]
// Define the type of the variable, give it a name, set it equal to the original variable with the cast in front of it.
ObjectYouWantItToBecome objectName = (ObjectYouWantItToBecome) theOriginalObject;

// For instance
double myDouble = (double) anInt;
int myInt = (int) aLong;
Ford aCar = (Ford) randomCar;

Now, to make your example work, you need to change two things.  First, the second apple (the double) can't have the same name as the first (the int).  Second, you need to place the name of the first behind the cast.  It'll look like this.
Code: [Select]
// Set an int with the name "apple" and the value 7
int apple = 7;
// Set a double with the name "apple2" and the casted value of apple, which is 7.0.
double apple2 = (double) apple;
Eclipse should have been yelling at you for duplicate variable names and not completing the double cast.

Casting primitives (usually ints and doubles) is a lot more common in my work.  I'm usually only casting Objects unless I have a darn good reason to.  Like if I'm overriding equals(Object).
Code: [Select]
public boolean equals(Object o) {
          Integer num = (Integer) o;
          boolean result = false;
          if(intValue == num.intValue) {
                    result = true;
          }
          return result;
}

Note that there is a difference between an int and an Integer.  An int is a primitive.  An Integer is an Object that acts essentially as a wrapper around an int so that it can be more easily used by things like Lists.
Code: [Select]
// This is illegal because a List cannot contain a primitive type.
List<int> myList = new ArrayList<int>();

// However, we don't need to pass it a primitive.  We have an object wrapper.
List<Integer> myList = new ArrayList<Integer>();

Technically speaking, you have to wrap/unwrap these things.  Like I talked about before, there's a lot of things that Java does for you.  This is another one of them.  If you want to know about wrapping/unwrapping/boxing/unboxing, let me know and I'd be happy to give a quick lesson.
Code: [Select]
// This is perfectly legal and completely common.
myList.add(15);

// When it should technically be...
myList.add(new Integer(15);

// It's boxing or wrapping for you in the first example.

// Now here, we're getting an Integer object and the system is unboxing or unwrapping for us.
int num = myList.get(0);

// Technically we should do that ourselves.
int num2 = myList.get(0).intValue;

Yes, there is in fact a Java class called Object.  It functions as the root of all classes.  At some point, you'll want to start looking at the Java API.  Technically, I linked you to the Java 7 API.  If you're using Java 6, you might find some things that didn't exist until Java 7.

You're extending JComponent.  What this means is that any method that exists in JComponent is inherited by your Object.  If you don't override the method in your object, it'll use the original. In order to override, you must use the exact same signature as the original.
Code: [Select]
// The Integer class contains these method signatures.
toString();
toString(int i);
toString(int i, int radix);

// Now, if I have an object that extends Integer, I have to override using the same signature as the original.
// For instance, if I want to override toString(int i), I need to implement something like the following
public static String toString(int i) {
          return i + "";
}
// The point being that I cannot change what it is I'm passing into the function.

// Incidentally, the idea of having several methods with the same name but different signatures is called Overloading.

What you're doing with paintComponent is overriding the original function.  In order to use the method, you have to pass it a parameter of type Graphics.  The good news is, you will (probably) never call paintComponent directly.  If anything, you're far more likely to call repaint().  The system will call paintComponent for you, it will find the Graphics object, and it will pass it for you.
Code: [Select]
// Like any function, you may or may not have to pass it parameters.
// It just happens that you have to pass a Graphics object so the system
// knows what it's painting on.  Of course, the system will find the Graphics
// object for you.  You should never have to call this method yourself
// and will use methods from the Graphics object to do your painting.
public void paintComponent(Graphics g) {
          // Draw Some Stuff
}

With the Graphics2D cast, it turns out that the Graphics object the system passes to paintComponent(Graphics) is actually a Graphics2D object that got cast back into a Graphics object at some point.  You just need to cast it forward again to get it back.
Code: [Select]
// ThingWeWant newName = (ThingWeWant) oldName;
Graphics2D g2 = (Graphics2D) g;

Okay, it's like 1:40AM, I think I'm going to lie down.  I'm happy to answer any questions you have.  You don't learn by not asking.  And seriously, at the point you're at, there is no such things as a stupid question.  Maybe I'm not the best at explaining if I'm failing to convey details, but I'm certainly willing to try.
Logged

Virex

  • Bay Watcher
  • Subjects interest attracted. Annalyses pending...
    • View Profile
Re: A question regarding learning Java
« Reply #11 on: September 14, 2011, 03:24:48 am »

Code: [Select]
public boolean equals(Object o) {
    Integer num = (Integer) o;
    boolean result = false;
    if(intValue == num.intValue) {
        result = true;
    }
    return result;
}


What's wrong with
Code: [Select]
public boolean equals(Object o) {
    Integer num = (Integer) o;
    return intValue == num.intValue;
}
« Last Edit: September 14, 2011, 03:26:42 am by Virex »
Logged

Arni

  • Bay Watcher
  • Soldier
    • View Profile
Re: A question regarding learning Java
« Reply #12 on: September 14, 2011, 03:55:31 am »

What's wrong with
Code: [Select]
public boolean equals(Object o) {
    Integer num = (Integer) o;
    return intValue == num.intValue;
}
A lot tidier and more compact. For beginners though harder to understand I guess.
Logged
Military and Militia. It's horrible

Stargrasper

  • Bay Watcher
    • View Profile
Re: A question regarding learning Java
« Reply #13 on: September 14, 2011, 08:25:26 am »

What's wrong with
Code: [Select]
public boolean equals(Object o) {
    Integer num = (Integer) o;
    return intValue == num.intValue;
}
A lot tidier and more compact. For beginners though harder to understand I guess.

Nothing's particularly wrong with the compact solution.  I chose not to suggest it for two reasons.
  • As stated, it's harder for beginners to understand.
  • The method I suggested self-documents better, which makes it easier to understand when referencing it later.
I actually consider the second to be more important.  I can get any beginner to understand anything for five minutes.  She will not remember it in six months and it does little good if she looks back at reference code and can't figure it out.  Strong comments alleviate this, but explicit code is still better for purposes of reference.

I will try to be as compact as possible in my own coding unless I've got a good reason not to.  But I'm also skilled enough to look at almost any Java code and figure out what it's doing.  This guy isn't to that point yet.
Logged

Virex

  • Bay Watcher
  • Subjects interest attracted. Annalyses pending...
    • View Profile
Re: A question regarding learning Java
« Reply #14 on: September 14, 2011, 09:18:43 am »

Meh, I guess you're right. Though it is also important to show people that you can use compound expressions in return statements, because that can save a lot of space. Besides, I find the terse version easier to understand as it requires one less variable and one less control block to keep track of and the compound expression is rather simple.

Also, can I get some more clarification on :
Code: [Select]
public void paintComponent(Graphics g) {?
As far as I can tell, JComponent was imported, and we're rewriting paintComponent. Then I don't get what's going on with "(Graphics g)".
And then what's going on with "Graphics2D g2 = (Graphics2D) g;"? So, are casts organized as
"ObjectToBeChangedInto ObjectToBeChanged = (ObjectToBeChangedInto) NewNameToBeStoredAs;"?
You explain the concepts very well, but the tiny things are getting me.
I'm sorry for being so difficult.
Java uses a strict ordering for assignment of new variables. First comes the type of the variable and then the name of the variable, followed by the =-sing and then what the variable should be set to. That name is introduced as a new variable.
So for example
Code: [Select]
Car MyCar = new Ford();
results in a variable called MyCar with the type Car, even though the object it refers to is a Ford (to which Car is a parent). This is because we're telling the compiler that we've got a variable that's of the type Car and the program will let you store any Car in that. Further more, MyCar is a car, not a Ford, so you can't do things specific for a Ford to it. So the following is allowed:
Code: [Select]
Car MyCar = new Ford();
MyCar.crashes();             //Damnit! Now I'm going to need a new one!
MyCar = new Opel();
because MyCar is defined as a variable that can hold cars and both a Ford and an Opel are cars. If we'd try the following:
Code: [Select]
Ford MyCar = new Ford();
MyCar.sell();                        //I got a raise, so I'll get a better car
MyCar = new AstonMartin();

that would result in an error because we told the compiler that MyCar can only hold Fords and now we're trying to put an Aston Martin in that variable.
And if we were to do this:
 
Code: [Select]
Car MyCar = new Ford();
FordGarage.doMaintenance(MyCar);  //The wheels fell off!

We'd get an error too, because MyCar is a variable holding a generic a Car (which happens to be a Ford in this case) and the Ford garage only does work on Fords. Since it only sees the type of MyCar, it thinks you're asking them to do maintenance on a generic Car, which they won't do. What we'd need to say is:
 
Code: [Select]
Car MyCar = new Ford();
FordGarage.doMaintenance((Ford) MyCar);  //And the petrol tank blew up!

Which means we cast MyCar to a Ford first and tell the Ford garage to do maintenance on it, which it'll happily accept because it's dealing with a Ford now.
Now the thing with casting is that if you cast something, you change it's type (assuming there is a way defined to go from the old type to the new type.) So the following code means:
Code: [Select]
double MyAge = (double) Player.getAge();
That you're getting the age of the player, which for the sake of this argument returns an integer, telling the program to cast it to a double. Then you tell the program that you add a new variable called MyAge, which is of type Double and finally you store the obtained double in the variable. From the last two examples you can see that it's not a strict order for assingment, but just because of the normal casting and assignment rules that you write "Type name = (type) object", because you always write "Type name = ..." and casting goes by saying "(type) object" (in this case object is an abstract definition for anything and everything you can use as data, so it'll work in integers just as well as on cars)
Logged
Pages: [1] 2