Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 136,057 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,576 people online right now. Registration is fast and FREE... Join Now!




Introduction to Designing Classes II

 
Reply to this topicStart new topic

> Introduction to Designing Classes II, Intro to designing class with static methods.

Locke37
Group Icon



post 30 Jul, 2008 - 03:22 PM
Post #1


Well, this is me second tutorial on designing classes with static methods. I'm gonna start you off with a very basic example: the Math class.

This class has methods that do mathematical calculations...I know...duh. Well, the methods of the Math class are static, meaning you don't have to instantiate an object to call them. You can simply call them like this.

java
Math.METHOD(parameters_used);


You DON'T have to do this:

java
Math mathObject = new Math();

mathObject.METHOD();


You don't HAVE to do it that way...but you can, but no one I know does that. smile.gif


Well, we'll make a method that does a very simple calculation. We'll make an addition() method.

java
class OurMath
{
public static int addition(int a, int cool.gif
{
int sum = a + b;

return sum;
}
}


Notice how we declare our int return type for the method. This makes it so we can assign it to an int variable in a main method or something.

Also notice the int variables in the parentheses. These are called 'parameters'. These are what's going to be included in the method when it's called.

It's going to be called like this.

java
int number = OurMath.addition(1, 3);


Well, anyone know what number is going to equal after that? That's right! Four!

You HAVE to call the method with 2 parameters. If you call it any other way, you're going to going to get a compile error saying something along these lines. cannot find symbol: method addition(int)


static Class Variables

Well, back again to the Math class. It has 2 double variables, E, and PI.

java
class Math
{
static double E = 2.718...;
static double PI = 3.141596535...;
}


This is how we declare static (AKA "class") variables. Let's go back to our class...

java
class OurMath
{
static int five = 5;

public static int addition(int a, int cool.gif
{
int sum = a + b;

return sum;
}
}


Well, now we can access our five variable through doing this.

java
int ourVariable = OurMath.five;


The main reason of using static is to make non "object"-ive data or methods.

Hope this tutorial helped anyone that needed it! biggrin.gif
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 12/1/08 06:03PM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month