Author Topic: [Java]Multiple Functions, Static Functions, Declaring Functions as Objects  (Read 13654 times)

0 Members and 1 Guest are viewing this topic.

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
I have a few doubts here:

Code: [Select]
public class Main extends JApplet {
    public static void main(String[] args) {
        MyFunction(); //This won't work
    }
    public void MyFunction() {
        System.out.println("Hello World");
    }
}

This won't work, I know I need to declare MyFunction as an object, but I'm not sure of how to do it :S


Spoiler For Spoiler:

package applettouppercase;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

//////////////////////////////////////////////////////////////// ToUpperCase
public class Main extends JApplet {

    //=================================================== instance variables
    private JTextField _inField  = new JTextField(20);
    private JTextField _outField = new JTextField(20);

    //================================================================= main
    public static void main(String[] args) {
        JFrame window = new JFrame();
        window.setTitle("ToUpperCase Example");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //... JApplet works fine as content pane in a window!
        ToUpperCase myToUpperCaseFunction = new ToUpperCase();
       

        window.pack();                       // Layout components.
        window.setLocationRelativeTo(null);  // Center window.
        window.setVisible(true);
    }

    //================================================== applet constructor
    public void ToUpperCase() {
        //... Create or set attributes of components.
        _outField.setEditable(false);    // Don't let user change output.
        JButton toUpperButton = new JButton("To Uppercase");

        //... Add listener to button.
        toUpperButton.addActionListener(new UpperCaseAction());

        //... Add components directly to applet.  Don't need content pane.
        setLayout(new FlowLayout());
        add(_inField);
        add(toUpperButton);
        add(_outField);
    }

    /////////////////////////////////// inner listener class UpperCaseAction
    class UpperCaseAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //... Convert text in one textfield to uppercase in another.
            String data = _inField.getText();  // Get the text
            String out  = data.toUpperCase();  // Create uppercase version.
            _outField.setText(out);            // Set output field
        }
    }
}

This is my proper code (in the spoiler) and the function I need to declare as an object in the Main function is ToUpperCase().

Thanks much.
   

Offline nemo

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1203
  • Rating: +95/-11
    • View Profile
i'm slightly confused. i know to make your code above work is declaring the method header of MyFunction as static, shown below
Code: [Select]
public static void MyFunction(){
}

you cannot "declare MyFunction as an object" as you put it. MyFunction is a method (java's word for subroutine or function) which cannot be instantiated as an object. in java, classes contain instance variables, 0 or more constructors, and methods. think of a class as a blueprint for an object. it tells the JVM how to instantiate an object.

i see you've found this site. its examples are well done and the site is helpful, though it lacks information about how OOP in java operates. Anyway, the problem with the code in the spoiler is that you're trying to make an object from class ToUpperCase, which does not exist because you have not defined it. if you notice, in the original example your code is from, the class name is ToUpperCase. you changed the class name to Main.
replacing
Code: [Select]
ToUpperCase myToUpperCaseFunction = new ToUpperCase();
with
Code: [Select]
window.setContentPane(new Main());

should fix the problem.


Offline Deep Toaster

  • So much to do, so much time, so little motivation
  • Administrator
  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 8217
  • Rating: +758/-15
    • View Profile
    • ClrHome
And Main is a reserved word in Java (for the main() function, which is run when a Java app starts). Even if you are allowed to use Main as the class name there, you're better off choosing a more descriptive name. The name of your class is going to be what objects of that class are called, remember.




Offline nemo

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1203
  • Rating: +95/-11
    • View Profile
Main isn't reserved, you can have a method called Main since java is case-sensitive. you cannot have another method "main" though. but you can have a variable "main" or an interface or class "main", though as Deep Thought said, it's not the best idea. the class name should reflect the type of objects the class is a blueprint for. it doesn't make sense to have a class called "Cereal" when the instance variables hold a string name, double GPA and an int gradeLevel. it makes more sense to name that class "Student".


Offline jnesselr

  • King Graphmastur
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2270
  • Rating: +81/-20
  • TAO == epic
    • View Profile
That's actually not entirely correct.  You can have many main functions, but only one is defined as THE main function that is called.

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MyFunction myToUpperCaseFunction = new MyFunction();
MyFunction();

}

public void MyFunction()
{
System.out.println("Hello");
}

}

It didn't really work, it says MyFunction cannot be resolved to a type :S

Offline jnesselr

  • King Graphmastur
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2270
  • Rating: +81/-20
  • TAO == epic
    • View Profile
Code: [Select]
Of course that won't work.  Because MyFunction needs to be a class.  What you need is this:
public class MyFunction {
public static void main(String[] args)
{
MyFunction myToUpperCaseFunction = new MyFunction(); // Create a new instance of this class called MyFunction.  I.E. calls the constructer.
}

public MyFunction() { // This is what is called when you call the "constructer" with no arguments. (Nothing inside the parenthesis)  Notice that there is no return type, as you are creating and returning an "instance" of the object MyFunction.
System.out.println("Object initiated");
}

}

Offline nemo

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1203
  • Rating: +95/-11
    • View Profile
That's actually not entirely correct.  You can have many main functions, but only one is defined as THE main function that is called.

true. i've never seen an overloaded main function though, probably because main isn't a very descriptive name for any situation, really.

and scout, you cannot instantiate an object from a method. this is the proper syntax:
Code: [Select]
ClassName objectName = new ClassName(<param list>);
(yes, i know you can do ClassName objectName = new SubClassName(), i'm keeping it simple.)

graphmastur has corrected your code in one way, here's another way you could do it without changing the class name:
Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MainClass myToUpperCaseFunction = new MainClass();
MyFunction();

}

public void MyFunction()
{
System.out.println("Hello");
}
}


Offline jnesselr

  • King Graphmastur
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2270
  • Rating: +81/-20
  • TAO == epic
    • View Profile
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

Offline nemo

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1203
  • Rating: +95/-11
    • View Profile
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function


Offline jnesselr

  • King Graphmastur
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2270
  • Rating: +81/-20
  • TAO == epic
    • View Profile
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
it doesn't have to have class in it at all.  If he wanted the class to be MyFunction, he should call it MyFunction, not MyClass.  a method is a function, yes.  But in this case it would be a method of the instance variable.  e.g.:
Code: [Select]
myToUpperCaseFunction.MyFunction();

Offline nemo

  • LV9 Veteran (Next: 1337)
  • *********
  • Posts: 1203
  • Rating: +95/-11
    • View Profile
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
it doesn't have to have class in it at all.  If he wanted the class to be MyFunction, he should call it MyFunction, not MyClass.  a method is a function, yes.  But in this case it would be a method of the instance variable.  e.g.:
Code: [Select]
myToUpperCaseFunction.MyFunction();

yes, that's what i was aiming for. i just realized MyFunction isn't static so my code won't compile, but regardless if i saw a class called MyFunction i would be confused.


Offline jnesselr

  • King Graphmastur
  • LV11 Super Veteran (Next: 3000)
  • ***********
  • Posts: 2270
  • Rating: +81/-20
  • TAO == epic
    • View Profile
^ Yes, that's another way.  The only problem is that MyFunction isn't your constructor, and so anyone outside the class that tried to insatiate it might not call MyFunction();

i just copy/pasted scout's code. i'm not sure if he wanted the class to be MyFunction (shouldn't it be MyClass, then?) or if he wanted MyFunction to be a method, which i thought made more sense because a method is essentially a function
it doesn't have to have class in it at all.  If he wanted the class to be MyFunction, he should call it MyFunction, not MyClass.  a method is a function, yes.  But in this case it would be a method of the instance variable.  e.g.:
Code: [Select]
myToUpperCaseFunction.MyFunction();

yes, that's what i was aiming for. i just realized MyFunction isn't static so my code won't compile, but regardless if i saw a class called MyFunction i would be confused.
True, which is why you name it after what it does.  not just MyFunction.  More like MyUberAwesomeReallyLongThisHasNoSpacesAndIsAPainToInitiateClass. ;-)

Offline Munchor

  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 6199
  • Rating: +295/-121
  • Code Recycler
    • View Profile
Thanks Much!

Now, can someone explain me what is going on here:

Code: [Select]
import javax.swing.*;       

public class HelloWorldSwing {
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("HelloWorldSwing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add the ubiquitous "Hello World" label.
        JLabel label = new JLabel("Hello World");
        frame.getContentPane().add(label);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Not the Swing Part, the way he calls createAndShowGUI() function.


But mainly thanks for:

Code: [Select]
public class MainClass {
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.MyFunction();

}

public void MyFunction()
{
System.out.println("Hello");
}
}

I'm making my class an object and accessing one of its properties, which is MyFunction() right?

Offline Deep Toaster

  • So much to do, so much time, so little motivation
  • Administrator
  • LV13 Extreme Addict (Next: 9001)
  • *************
  • Posts: 8217
  • Rating: +758/-15
    • View Profile
    • ClrHome
I'm making my class an object and accessing one of its properties, which is MyFunction() right?

Well, not really. A class is like a definition, creating a new type of object. Then the line MainClass mainClass = new MainClass(); creates a new instance of the class -- an object. That object is a MainClass object, which has a function called MyFunction, so you're calling that with mainClass.MyFunction();.

I think you'll understand it better if we use a concrete example. Say you want to represent buying a car with Java. First, your Car class defines what a car looks like, what you can do with it, etc.

Code: (Java) [Select]
public class Car
{
    public String make;
    public String model;
    public boolean working;    // Set up the variables of the class.
   
    public Car(String arg1, String arg2)    // A constructor; it gets called when a new Car object is created to set up some of the new Car's variables.
    {
        this.make = arg1;
        this.model = arg2;
        this.working = true;
    }
   
    public void dispMakeModel()
    {
        if (this.working)    // First check if it works or not.
        {
            System.out.println("This car seems to be a " + this.make + " " + this.model + ".");
        }
        else
        {
            System.out.println("This car is broken! Fix immediately!");
        }
    }

    public void drive()
    {
        this.working = false;    // Car no longer works.
        System.out.println("CRAAASH!!!11");
    }
}

That's a complete definition for the Car class. If you want to do something, make a main function:

Code: (Java) [Select]
public static void main(String[] args)
{
    Car myPrecious = new Car("Ford", "Fusion");    // Creates ("buys") a new car with make "Ford" and model "Fusion". Notice that there are two arguments, because the Car constructor above takes two arguments.
    myPrecious.dispMakeModel();     // Displays the string "This car seems to be a Ford Fusion."
    myPrecious.drive();     // Take it out for a drive. Oh darn, you crashed.
    myPrecious.dispMakeModel();     // This time it displays "This car is broken! Fix immediately!"
}

That's what's great about Java: you can represent anything you want by defining a class for it :D