PDA

View Full Version : Java Classes




Jasonbot
Nov 12, 2007, 09:28 AM
Hi guys, I'm writing my end of year java exam tomorrow and only heard today that I'm supposed to learn about using multiple classes in java. Could someone please show me in general how to use multiple classes?

Also, in classes does the same rule apply as in methods whereby variables can only be used with a single method unless they're static?

What is the purpose of having multiple classes?

When running a method from another class do I go class_name.method_name(); ?

Thanks guys.

On a side note, how does the 'extends' thing work with classes?

I found this on wikipedia:

public class Example1
{
// This is a Java class, it automatically extends the class Object
public static void main (String args[])
{
System.out.println("Hello world!");
}
}

public class Example2 extends Example1
{
// This is a class that extends the class created in Example 1.
protected int data;

public Example2()
{
// This is a constructor for the class. It does not have a return type.
data = 1;
}

public int getData()
{
return data;
}

public void setData(int d)
{
data = d;
}
}

after the method Example2() runs does getData() run directly afterwards?



pilotError
Nov 12, 2007, 09:48 AM
Short answer is you have to instantiate it and do something with it.

If you just compiled / ran the example you gave, it would just print hello world.

If you did something like:


Example2 myEx2 = new Example2();

myEx2.setData(5);

Sytem.out.println ("Data: " + myEx2.getData());


Essentially you would have to override the main() to do something with it, or use it as part of a method.

Your example is called inheritance and you use it to extend the functionality of a class.

hankolerd
Nov 12, 2007, 10:03 AM
when you use the command "extend" it takes every function from example1, and carries it over to example 2, thus the main function in example1 is pulled into example2 class. But everything inside of example2 are functions, except for the first function which is called a constructor, which is how you initialize an example2 objects, much like you would say int i = new int(0); or int i = 0; which both do the same thing. you could say example2 bean = new example2(); bean.setdata(10);(or whatever that function was called).
The rest of the functions only run when called. Java only runs code inside the main function by default, by calling a function in main, you will go there, and execute the code in that function, and then return to main, unless you call another function from the first function call.

Hope this helps in some way.:apple:

kainjow
Nov 12, 2007, 10:32 AM
On a side note, how does the 'extends' thing work with classes?) runs does getData() run directly afterwards?

Conceptually it's called Polymorphism (http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#Consider_it_in_Java:) (link points to Java examples).