Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Jasonbot

macrumors 68020
Original poster
Aug 15, 2006
2,467
0
The Rainbow Nation RSA
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:
Code:
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

macrumors 68020
Apr 12, 2006
2,237
4
Long Island
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:

Code:
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

macrumors 6502
Sep 19, 2007
353
6
Seattle, WA
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:
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.