
-----------------------------------
Aange10
Tue Dec 20, 2011 11:12 pm

Syntax Problems
-----------------------------------
Okay, so, I have two classes inside a project. One class is holding an object called Dog. The class looks like this:


public class Dog {
	int age;
	String name;

	void Bark() {
		System.out.println("WOLF WOLF!");
	}
}


my other class is where my 'Main' is going to be, and it looks like this:


public class Loopy {
	Dog anthony = new Dog();
	{
		anthony.name = "Anthony";
		anthony.age = 6;
	}

	public static void main(String

In my PDF, it does something like this (it's poorly written; they just throw chunks of code without headers around, so I begin to get confused on how I connect the peices). But I'm getting the syntax error 'Cannont make a static reference to a non static field anthony.' I read the documentation for Java's Static, and they did an example just like this:


static methods and variable are in a sense inherited, but not in the same strong sense that instance variables and methods are. You can refer to Dog.bark() as Dalmatian.bark() if no one has written a Dalmatian.bark(). However, if you use Dog.bark() you always get the Dog version and if you say Dalmatian.bark() you always get the Dalmatian version.



After reading the documentation, I'm not sure what the problem is. I tried running the anthony.Bark(); without calling main but It was an error too. I also tried making void Bark() { into static void Bark() { but that didn't fix the problem (it still gave me the same syntax error).


Could anybody help me with seeing what the problem is with my method? Are both of my classes formatted correctly?

Also, in the PDF it does 


	Dog anthony = new Dog();
	{
		anthony.name = "Anthony";
		anthony.age = 6;
	}


as


	Dog anthony = new Dog();
        anthony.name = "Anthony";
	anthony.age = 6;


why does it give me an error, but the pdf says it's good? (As I said the pdf shows a lot of blocks of code, without showing the headers etc. So It's hard to piece it all together.)


Thanks.

-----------------------------------
crossley7
Tue Dec 20, 2011 11:26 pm

RE:Syntax Problems
-----------------------------------
I happened to see this and although I haven't used Java much, I can see if I can help you debug a little bit.  I think the problem is in relation to this section of code.

 Dog anthony = new Dog(); 
        { 
                anthony.name = "Anthony"; 
                anthony.age = 6; 
        } 

Generally at least in C++ classes (sorry, only reference I have other than really basic Java) those 2 lines of code inside the {} have to be within a function which in this case they are not.

Another issue that could be it (I discarded initially but will mention it anyway) is that anthony is a member of loopy.  It shouldn't be an issue since it is within the same class but I'm never 100% sure.  Also, might be something with the class names?  main seems to have additional importance in a program and so you might just need to rename the second class.  Once again, sorry if these are really dumb suggestions.  I need to actually figure out Java before making educated guesses based on my knowledge of other languages.

-----------------------------------
Aange10
Tue Dec 20, 2011 11:40 pm

RE:Syntax Problems
-----------------------------------
the 

Dog anthony = new Dog();
{
anthony.name = "Anthony";
anthony.age = 6;
} 


Honestly doesn't make sense to me either, but if I don't add the { and }, it gives me a syntax error. The pdf doesn't do it that way, but the way the PDF does it gives me a syntax error.

-----------------------------------
DemonWasp
Tue Dec 20, 2011 11:43 pm

RE:Syntax Problems
-----------------------------------
It seems you don't really understand what "static" means...and I can't blame you, that copy-paste stuff from your PDF is awful (if technically correct).

Every field in a class is either an instance field or a static field. The same applies to methods: there are instance methods and static methods and no other kinds of methods. The default is instance; to make something static, you add the static keyword.

Instance means one-per-object. That is, every dog has a name, and they can have different names. Similarly, every dog has an age, birthdate, favourite toy, etc. These are wrapped together by an instance of the Dog class. You create a new instance every time you use the new keyword.

Static means one-per-type. That is, only one copy, no matter how many dogs you have. Use these to describe data or behaviours that are shared across all objects of that type. Methods like Math.abs(x) and Integer.parseInt("123") are static because you don't need an instance of the Math class to know how absolute value works. It's in the Math class so that everything remains organised into logical units (Math, Integers, Doubles, etc).

You cannot override a static method. You can override instance methods. You can overload both.

A static method exists as soon as the type exists ("always", until you get really advanced). An instance field only exists when an instance of the object exists.

Your problem is that this:

public class Loopy { 
    Dog anthony = new Dog(); 
    { 
        anthony.name = "Anthony"; 
        anthony.age = 6; 
    }
    //...
}


Defines an instance field, "anthony", inside the Loopy class. Therefore, every time you make a new Loopy(), it will automatically create a new Dog() and assign it the name "Anthony" and the age 6.

However, you never make any Loopy instances. The main method is static, which means it can be called without creating any Loopys at all. What you need to do is create your Dog instance inside your main() method. An alternate approach that works, but isn't as good, is to make anthony static, which means that it exists as soon as the Loopy type exists.

Your other question is presumably about this:

public class Loopy {
    Dog anthony = new Dog(); 
    anthony.name = "Anthony"; 
    anthony.age = 6; 
}


The reason that doesn't work (but the one with the braces does) is because this version has statements (assignments, specifically) happening outside of a method or initializer. The line "Dog anthony = new Dog();" is okay because it's a variable declaration with initialization. The next two lines are statements, and are not permitted there. Wrapping them in braces produces what's called an "initializer block" (see: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html). I've never seen one in actual use before (though I have seen static initializer blocks).

-----------------------------------
Tony
Tue Dec 20, 2011 11:49 pm

RE:Syntax Problems
-----------------------------------
@crossley7 -- {} define a block which can do anywhere a statement goes. Even in C++


McEpic:tmp tony$ cat test.cc 
int main(){
  int x = 1;
  {
    int x = 2;
  }
  x++;
  return x;
}

McEpic:tmp tony$ g++ test.cc 
McEpic:tmp tony$ ./a.out 
McEpic:tmp tony$ echo $?
2


@Aange10 --

error 'Cannont make a static reference to a non static field anthony.'

means that the field "anthony" is part of an instance of Loopy, while "public static void main" is a static method -- that is, it belongs to the class.

Even though you might have only a single instance of Loopy, the program can't know that you will not have another at some future point. As such, the shared static method can't know which "anthony" you might be referring to.

-----------------------------------
Zren
Tue Dec 20, 2011 11:53 pm

RE:Syntax Problems
-----------------------------------
{} are used for scope. A static field requires something like this:


public class Loopy { 
        Dog anthony = new Dog(); 

        static { 
                anthony.name = "Anthony"; 
                anthony.age = 6; 
        } 

        public static void main(String

However in this case, anthony hasn't been declared (as it's an instance variable). What you should be doing, is creating a static function to set those values and call it first. What you should really be doing is making a constructor for the Dog class.

Also, you can't do more than declare (and initialize) class members within the class's 'outer' or 'root' scope (not entirely how to define this, maybe 'field'?). That's why you can't define a variable on one line (with a closing statement ';') and assign it on another line.

A good question would be to check if they're running a different/older version of Java.

-----------------------------------
Aange10
Wed Dec 21, 2011 12:05 am

RE:Syntax Problems
-----------------------------------
Confusing.

Okay so


Dog anthony


is assigning a variable named anthony to a type Dog, correct?

and then


anthony = new Dog()


is making anthony, whos type is Dog, an instance of Dog.

That confuses me. If the class file was animal, with Dog in it, would I say


animal anthony = new Dog();

?

Right I understand what a type is, but not a reference type. That is, I'm not sure the difference between defining something as a reference to something, and making an instance of something.

Wherein my confusion of that,


Instance means one-per-object.

Static means one-per-type


makes this very unclear.

An instance of something is just an object of it right? Like a child of it?


And my origional problem was that I was defining a new class (loopy) instead of defining a new instance of Dog? [Well, I did both]


EDIT: To clarify what I was trying to do: all I'm trying to do is make an object of dog, named Anthony, define its instances, then call its method.

-----------------------------------
DemonWasp
Wed Dec 21, 2011 3:33 am

Re: RE:Syntax Problems
-----------------------------------
Hmm. You also seem to be confusing "instance", "type", and a few other concepts.

A "type" is a way of arranging information. An int is a type that can hold integers in a certain range. A double can hold real numbers. A String can hold a series of characters. A Dog holds a name and an age.

An "instance" is one particular thing of a type. An "instance" of an integer might be the number 3. An instance of a double could be 3.1415. An instance of a string could be "FooBarBaz". An instance of a Dog could have the name "anthony" and the age 6. A different instance could  have name "Rover" and age 2.

An instance is NOT a child of its type. It is an instance of its type. For example, you and I are both humans. We could be represented by two instances of the Human class. We have type Human, and you could say "Aange10 and DemonWasp are (instances of) Human". If you changed the type Human, we would both have the same changes.



The difference between a primitive type (boolean, byte, short, int, long, char, float, double) and a reference type (String, Object, anything you define) is a little tricky to understand:

A primitive type is the simplest form of information you can store. They are each exactly one thing. For example, an int holds an integer number. A double holds a real number. A char holds a single character. They don't have additional information stored in them (unlike Dog, which has name and age and ...).

A reference type is any type that isn't primitive. All reference types extend from Object (potentially through several layers), even when they don't explicitly say so. If you say:

public class Dog {
}

Then Dog extends Object.

The difference is only important occasionally. It is most important when passing things to methods. For example:


public class Foo {
    public static void main ( String

But:

public class Foo {
    public static void main ( String
Right before Java finishes running "myMethod", it will have two instances of Dog. The first is the Dog d in main, and it has the name "Rex". The second is the Dog d in myMethod, and it has the name "Fuzzy".



To extend your example, let's assume you have defined two types of your own: Animal and Dog. Now, all animals will have an age and a name:

Animal.java:

public class Animal {
    String name;
    int age;
}


Dogs may have other information in addition. However, a Dog is-a(n) Animal. All Dogs are Animals, but not all Animals are Dogs (some are Cats, etc). So:

public class Dog extends Animal {    // because all Dogs are Animals
    String favouriteToy;
}




The words "define", "declare", "initialize" and "assign" have very specific meanings:

You define a type when you list what fields and methods it has. For example, you have defined Dog to have fields "String name" and "int age" and methods "void Bark()".

You declare a variable when you give its type. For example, "Dog myDog;" is a declaration of a variable named "myDog" of type Dog.

You initialize a variable when you first assign it. Often, you do this on the same line as the declaration: "Dog myDog = new Dog();".

Do Not*:
You never define an instance.
You never declare an instance.
You never initialize a type.
You never assign a type.



As for your original problem:
And my origional problem was that I was defining a new class (loopy) instead of defining a new instance of Dog? 

None of that makes sense. What you are trying to do is:
1. Create a new instance of Dog.
2. Assign the Dog's name the value "Anthony".
3. Assign the Dog's age the value 6.
4. Call the bark() method of the Dog.

So, go put code inside the main method that does this.


* For advanced Java programmers only: you almost never do those things.

-----------------------------------
2goto1
Wed Dec 21, 2011 7:53 am

Re: RE:Syntax Problems
-----------------------------------


That confuses me. If the class file was animal, with Dog in it, would I say


animal anthony = new Dog();

?


Class file names are simply conventions. The source code file names do not define your Java types. If you really wanted to for fun and giggles, you could place your Dog class definition inside a Cat.java source file. You would still have just a Dog type that you could instantiate using the new operator. But you would not have a Cat type that you could instantiate with the new operator. You would not have a Cat namespace. Java would not know of the existence of Cat in any way, shape, or form. 

Java packages and classes typically have a 1:1 relationship with your project's directory and file structure. That is, your Dog class will almost always reside in your Dog.java source file, and your Cat class will almost always reside in your Cat.java source file. It makes your projects much easier to maintain. It's a convention for organizing your source code, since Java, like many other programming languages, relies on your OS file system to keep source code organized.

If the source code file name was animal.java, or Cat.java, and the source code file contained just your Dog class definition, then you would say:


Dog anthony = new Dog();


-----------------------------------
Aange10
Wed Dec 21, 2011 12:46 pm

RE:Syntax Problems
-----------------------------------
Thanks all of you for your help, especially Demonwasp. I'll probably have more problems -- probably within a few hours -- so I'll be posting a lot of [basic] questions.

Thanks.

-----------------------------------
Aange10
Thu Dec 22, 2011 5:59 pm

RE:Syntax Problems
-----------------------------------
Another problem;

Firstly, I have a question (as it is my hunch to why this isn't working), when I have a method for an object, and in the method I call one of the object's instance variables, will it call the correct number?

Example (My Problem);

I have a class Math, that looks like:


public class Math {
	int int1, int2, int3;
	double fahrenheit, celsius;
	void PrintSolution (){
		System.out.println ((int1 * int2 * int3));
	}
	void PrintConverterFtC (){
		double tempnum = (5/9) * (fahrenheit - 32);
		System.out.println ("The degrees " + fahrenheit + " fahrenheit is equal to " + tempnum + " degrees celsius.");
	}
}


If in another class I make a new instance of Math, will the fahrenheit variable in the PrintConverterFtC method hold the value of of the new instance of Math's value?


public class Main {
	public static void main (String 

-----------------------------------
Tony
Thu Dec 22, 2011 6:11 pm

Re: RE:Syntax Problems
-----------------------------------
If in another class I make a new instance of Math, will the fahrenheit variable in the PrintConverterFtC method hold the value of of the new instance of Math's value?
Yes, this is how instance variables work.

Ninja edit: to be clear, we are talking about PrintConverterFtC of the new instance, not of the old instance. The old method will still have its own variable to work with.

-----------------------------------
Aange10
Thu Dec 22, 2011 6:33 pm

RE:Syntax Problems
-----------------------------------
So, in my Main class I defined foo.fahrenheit as 45, then I run foo.PrintConverterFtC, and it outputs 0. Which, clearly, (5/9) * (45 - 32) isn't 0. (it's 7.2)

I must be misunderstanding you.

-----------------------------------
Zren
Thu Dec 22, 2011 6:41 pm

RE:Syntax Problems
-----------------------------------
5/9 is integer division, which gives 0. You need to cast the later part to a real type. Since you're using a hardcoded number you can just do either of the following.

5 / ((double)9) // Cast the integer to a double
5 / 9.0 // 9 is a real number (double)
5 / 9D // 9 is a double

-----------------------------------
Aange10
Thu Dec 22, 2011 6:50 pm

RE:Syntax Problems
-----------------------------------
Thankyou, Zren, and for future reference, would 5.0/9.0 work?

Also, say that it was all variables, and not hardcoded, would it be reccomended that I did ((double) var5/var9)?


Thanks.


EDIT: 5/(double(9)) is a syntax error.

EDIT again: How would I make it only show two decimal spots?

-----------------------------------
Zren
Thu Dec 22, 2011 7:03 pm

RE:Syntax Problems
-----------------------------------
A) Yes that would work. The top of the fraction doesn't necessarily need to be a real number too, just one side of the fraction.

B) If you wanted to use an integer variable for the bottom, yes you'd need to cast it as a double first if you wanted decimal values. However, understand that what you just wrote is casting 5 as a double, then dividing by the integer 9 (not integer division as top is double). It's not casting the entire fraction.

-----------------------------------
Aange10
Thu Dec 22, 2011 7:13 pm

RE:Syntax Problems
-----------------------------------
I see, thank you for that; (((double)5)/((double)9)) * (fahrenheit - 32.0) now works perfectly. How would I make it, when I output it, only show two decimal places?

-----------------------------------
Zren
Thu Dec 22, 2011 7:32 pm

RE:Syntax Problems
-----------------------------------
Read up about all the awesomeness available with String.format() here:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

String.format("%.2f", 9.2348209);

-----------------------------------
Aange10
Thu Dec 22, 2011 9:39 pm

RE:Syntax Problems
-----------------------------------
Thanks for that. The string format is pretty cool, and I can use it just like Str.Lower(). (I believe it also has a function like that).


Anyways, to another problem! I despise this, because the problems are so stupid. Its less embarrassing when it's the algorithm messing things up, not the ignorance.

So this problem makes absolutely no sense to me. There are no errors, and I've traced my algorithm with comments. Its super simple, it won't output to the screen! But I don't see why, everything is nested correctly.

Once again I have two classes, Main and Sort. Main is easy and looks like this:


public class Main {
	public static void main (String 

Just making an instance of Sort, and calling one of its methods.

This is the sort class. I have the algorithm traced, though my problem isn't whats being computed. It's the fact that it won't even print to the screen! (Makes me think I have some brackets messed up but I don't):


import java.util.Scanner;


public class Sort {
	
	void Sort10 (){
		
		int num



Also, on a side note, I imported Scan. Is that only going to be valid for the objects in the class I uploaded it to, or will it be valid for my entire program?

-----------------------------------
Tony
Thu Dec 22, 2011 9:59 pm

RE:Syntax Problems
-----------------------------------

The scope of a type imported by a single-type-import declaration (?7.5.1) or a type-import-on-demand declaration (?7.5.2) is all the class and interface type declarations (?7.6) in the compilation unit in which the import declaration appears.


-----------------------------------
Aange10
Thu Dec 22, 2011 10:05 pm

RE:Syntax Problems
-----------------------------------
does this have to be on the heap" What do you mean? And I think the syntax might be int   ... but neither give me a syntax error. And with that change, it doesn't go past the for. whats wrong with the for...?

-----------------------------------
DemonWasp
Thu Dec 22, 2011 10:05 pm

RE:Syntax Problems
-----------------------------------
You have at least two problems:
- your array isn't 0-9, it's 0-8 (9 items)
- your for loops never execute because their "continue" conditions (middle) are wrong

To make what Tony said more apparent: imports only apply to the contents of that file. They affect anything within the file, but not the rest of your program.

@Tony: are you forgetting your Java? Java uses new for everything, and everything works like it's on the heap, even when it doesn't end up getting allocated there.

-----------------------------------
Aange10
Thu Dec 22, 2011 10:11 pm

Re: RE:Syntax Problems
-----------------------------------
You have at least two problems:
- your array isn't 0-9, it's 0-8 (9 items)
- your for loops never execute because their "continue" conditions (middle) are wrong


Ahh thanks so much.

A: I didn't know that stopWhenThisIsTrue not continueUntillThisIsFalse


Thanks, both of you.

-----------------------------------
Tony
Thu Dec 22, 2011 10:23 pm

Re: RE:Syntax Problems
-----------------------------------
@Tony: are you forgetting your Java? Java uses new for everything, and everything works like it's on the heap, even when it doesn't end up getting allocated there.
Hah, you're right :lol: I've been writing nothing but C and C++ for the past 4 months.

-----------------------------------
Aange10
Thu Dec 22, 2011 11:08 pm

Re: RE:Syntax Problems
-----------------------------------

Hah, you're right :lol: I've been writing nothing but C and C++ for the past 4 months.

Aren't you a ruby dev?

-----------------------------------
Tony
Thu Dec 22, 2011 11:32 pm

RE:Syntax Problems
-----------------------------------
Ruby is typically my language of choice, but there isn't much say in school assignments ;)

-----------------------------------
Aange10
Fri Dec 23, 2011 1:23 am

RE:Syntax Problems
-----------------------------------
A bit OT, but java is really amazing. I can't wait until I learn all the syntax (well, enough).

It's very clean. Everything being so organized by brackets, being stifled into classes is nice. If I want 80 dogs, I don't have to worry about their names getting jumbled, or making sure Dog 70 doesn't have a number in his name; they do it themselves. The classes can take care of them selves. It's a lot different than micromanaging every bit of information you use.

It's amazing you can make a method with parameters to define your instances for you, and if you're using eclipse, when you type up the method it'll lay out the syntax of the arguments for you. It's like a one line initialize, that can be bullet proofed in the method (if you like, and whatever else), and the layout is given to you, so you don't forget a variable. Don't want to assign one? Simple use an if param != null.

Java is really neat in the way it works. I'm eager to experience the inheritance aspect.

So to put this a tad bit on topic, If I make a class Animal with a name and age, and a breathe method - and I decide to make another class Dog, how do I make it inherit from Animal? Because I'd like to give all Dogs the bark method, and favorite toy instance as well(:

-----------------------------------
Tony
Fri Dec 23, 2011 1:26 am

RE:Syntax Problems
-----------------------------------
[code]
public class Dog extends Animal { ...
[/code]

-----------------------------------
Aange10
Fri Dec 23, 2011 1:30 am

RE:Syntax Problems
-----------------------------------
extends! Ahh, I see. Thanks.

-----------------------------------
Aange10
Fri Dec 23, 2011 11:13 pm

RE:Syntax Problems
-----------------------------------
And onto another question:

Does java have a way to detect if a variable has a value? For instance I'd like to make my method look like this:


public void applyMonthlyInterest (){
               // savingsBalance is an instance of the class holding this method, and it is a double.
		if (savingsBalance != null){
		savingsBalance = ((savingsBalance) * (annualInterestRate/12.0));
		} else {
			// error
		}
	}


However this is obviously is an error because a double can't have a value 'null'. Is there a way I can make sure that the variable has a value?

-----------------------------------
Tony
Fri Dec 23, 2011 11:21 pm

RE:Syntax Problems
-----------------------------------
for primitive data types, no. Though you can use object versions of those types, e.g. java.lang.Double where null makes sense.

-----------------------------------
Aange10
Sat Dec 24, 2011 12:48 am

RE:Syntax Problems
-----------------------------------
Okay thank you, Tony.


About static and instance variables/methods, is this valid:

I have a Dog class and I make its Breathe() method static because all dogs will breathe the same (lets say). And I make a run() method an instance method because all dogs run at different speeds.

To my understanding, Breathe() would be defined as soon as it was written, whereas run() would have to be defined within another object . So, then, to call Breathe() I'd say ClassName.Breathe(), and to call run() I'd call ObjectName.run(), but I can't say ClassName.run() or ObjectName.Breathe(). Is this all correct? Because this is my current understanding.

Also, why would I want a static method? Why would I need to call ClassName.breathe() if I didn't have an object of the class?

You cannot override a static method. You can override instance methods. You can overload both. 

 How would I override a method? When would I want to, really? If my run() method went off a speed instance variable, what would be the purpose of making run() an instance method? And finally, what does it mean overload both? I'm not really sure of what that would be referring to. 

Thanks in advanced

EDIT: Is the point of a static variable that I can edit it for all the objects, both current and future, at once? (I just did this). But if I can't do that for a method, I don't see the point.
EDIT2:  I changed the static variable by making a method to do so. I have a 'BankAccount' class, with a static variable Interest. And I have a method to change Interest.

-----------------------------------
Tony
Sat Dec 24, 2011 1:17 am

RE:Syntax Problems
-----------------------------------
Think of it this way: you've started out with Procedural programming, mixing code and data one line after another. Everything was flowing in one direction, so it sort of worked.

At some point you've discovered Types/records. Woah, whole new way to group and organize data together! A single array of points, instead of separate Xs and Ys that must be kept in sync.

Object Orientation takes it a step further. Now instead of grouping together and organizing data, you also get to group together and organize code!

Woah, what? Yup. A particular function can actually belong to the concept of that same "point" type, and be usable only by points. Previously functions had global scopes, and were available for use from the entire project in unexpected ways.

You want static methods when the code has to do with the entire class. A good example would be a method that returns the total number of dog instances created so far. This is a property of the class, not of an instance. It still makes sense to call Dog.count_of_dogs() and have it return 0.

Breathe() on the other hand should be an instance method as, conceptually, such an action is a property of an individual dog (an instance). You want to be able to say: Fido.breath(). It wouldn't make much sense to tell "the concept of a Dog" (what a class is) to breath.

-----------------------------------
Aange10
Sat Dec 24, 2011 1:44 am

RE:Syntax Problems
-----------------------------------
I see, that makes much more sense. The Dog.count_of_dogs() example really clears it up.

But I'm still curious of the two things Demon Wasp said.


... How would I override a method? When would I want to, really? ...  ... And finally, what does it mean overload both? I'm not really sure of what that would be referring to. 


Thanks xD. 

OT: I always question everything. Even in math class, or anything along those lines, I always want to know how things work. I don't like the concept of "this works, this is how you use it, go." I always want to know in what ways I can manipulate it, and why it does what it does (and usually how)...

-----------------------------------
Tony
Sat Dec 24, 2011 2:05 am

RE:Syntax Problems
-----------------------------------
Sure.

You override a method when you extend another class, and re-implement a method that the parent had already defined. E.g.
final keyword)

An overload is for differently typed arguments:
[code]
class Dog {
   String run(int speed) {
      return Integer.toString(speed) + " units per whatever";
   }
   String run(String description) {
      return description;
   }
}
[/code]

-----------------------------------
Aange10
Sun Dec 25, 2011 1:31 pm

Re: RE:Syntax Problems
-----------------------------------
Class file names are simply conventions. The source code file names do not define your Java types. If you really wanted to for fun and giggles, you could place your Dog class definition inside a Cat.java source file

How so? This provides an error: "Public class Dog must be defined in its own file".

-----------------------------------
Tony
Sun Dec 25, 2011 2:23 pm

RE:Syntax Problems
-----------------------------------
http://java.sun.com/docs/books/jls/third_edition/html/packages.html#26783

When packages are stored in a file system (?7.2.1), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

 - The type is referred to by code in other compilation units of the package in which the type is declared.
 - The type is declared public (and therefore is potentially accessible from code in other packages).

So matching filenames are enforced by the specification, with the exception of private class declarations that are not referred to by any other compilation units.

Meaning that you could have a private Dog class inside of Cat.java... but unless there's a public Cat class, Dog's code is not reachable.

-----------------------------------
2goto1
Mon Dec 26, 2011 10:31 am

RE:Syntax Problems
-----------------------------------
The specification allows compilers to opt into the rule if they wish (...may choose...)

-----------------------------------
Tony
Mon Dec 26, 2011 2:09 pm

RE:Syntax Problems
-----------------------------------
sure, you could probably find some compiler that doesn't follow some spec, but if you expect other people to compile your code without jumping through the hoops of installing and running an esoteric compiler... you should probably stick to the standard Java, as defined by the spec. That includes filenames. E.g. javac

tony$ javac Foo.java 
Foo.java:1: class Boo is public, should be declared in a file named Boo.java
public class Boo {


-----------------------------------
Aange10
Mon Dec 26, 2011 3:51 pm

RE:Syntax Problems
-----------------------------------
Makes sense.

-----------------------------------
2goto1
Mon Dec 26, 2011 4:03 pm

RE:Syntax Problems
-----------------------------------
Yep, bad idea in general

-----------------------------------
Aange10
Fri Jan 06, 2012 10:27 pm

RE:Syntax Problems
-----------------------------------
Yay, time for another question.

Upon doing some reading about java, I came across an article stating the following.


What Constructors Do

Constructors may contain code that is run when the object is created. It is sort of like setup code that you want done so the object is ready for what it's supposed to do.

Here's an example of what I'm talking about:




The 
package society;
public class Human (){
    private string  Gender;
    public Human (){
        Gender = "Male";
    }
}


Upon reading this, the first sentance really struck me;

"Constructors may contain code that is run when the object is created."

I tested this theory, and when I have code (Say a class, with an instance age and a method looking like the above defining Age as 1), the code does not 'Run when the Object is Created".

I tested this by creating a new object of Dog and outputing its age. However it didn't output one, meaning that the code was NOT run when i created the new object.

Am I doing it wrong, am I misunderstanding, or is this passage inaccurate?

-----------------------------------
DemonWasp
Sat Jan 07, 2012 12:35 am

RE:Syntax Problems
-----------------------------------
You should probably post your code. You probably made a minor mistake (such as the 3 in the example you copy-pasted). A constructor must have the same name as the class, must not list any return type (not even void) and should probably be public (at least, for now: there are plenty of reasons for non-public constructors, but let's not get into that).


public class Dog {
    private int age;

    public Dog() {
        System.out.println ( "no-argument constructor" );
    }

    public Dog ( int dogAge ) {
        this.age = dogAge;
        System.out.println ( "one-argument constructor: dog has age " + age );
    }

    public void Dog ( String name ) {
        // not actually a constructor because of the "void" return type
    }

    public static void main ( String
