DEV Community

loading...

Java: Functions in your own class

Yuri Filatov
Hey, I am an IT Expert and IT Delivery Manager at Andersen
Originally published at andersenlab.com Updated on ・2 min read

The best exmaple of usage of your own class is to work with a database. Moreover, using functions in class is more correct than simple functions anyway.

Let's work on the example of database.

What is a database?
Imagine some tour-company website, where you see many tour names, date, price and so on. So a simple mas is not good enough to keep all this information.

Step 1.
Decide which values you have.
Here:

Name of tour - string
Date - can be string if you don't need to make changes, but better to use calendar/date.
Price - double

Step 2.
Make a class with this values.
As we have a lot of string values, we need a mas of string, hopefully, everyone understand it.

class Tour_Data_Base () {
String[] name = new String[any length];
String[] date = new String[any length];
double[] price = new double[any length];
...
}

Step 3.
Start making functions below the initialization.
First function must be reading so to complete our database.
Functions for reading you can find in previous articles, but here there is a little difference.
It is incorrect to write just the name of variable, cause it is in your class, so you must write the "direction"

Instead of name=...; write this.name=...;

Step 4.
Call functions written in your class correctly.
Initialize the object of your class.

Tour_Data_Base data = new Tour_Data_Base();

If your function is with empty brackets, then when you call it, your brackets are also empty.

void Read_File () {
... }

In Main:

data.Read_File();

If the brackets are not empty, then in the Main function, when you call a class function, they are also not empty.

void Read_From_Console (String name, String date, double price) {
... }

A small tip: name that you send to a class function is not the same with name initialized in your class function.
So here you have to initialize this variables (String name, String date, double price) in Main to send to the class function.

Scanner in = new Scanner(System.in);
String name = in.nextLine();
String date = in.nextLine();
double price = in.nextDouble();
data.Read_From_Console(name,date,price);

I hope it was useful for those, who want to make their first steps. If you have any questions, write me anytime.

Good luck in your job!

Discussion (0)