Alexander Demerdzhiev
Alexander Demerdzhiev

Reputation: 1044

Importing a class in java

I'm new to java and don't really understand all the written things for importing class so i need a specific example to show me how to import a class and create an object of the external class in my main method.

Here is my code :

public class MainClass {
  public static void main( String[] args) {
    System.out.println("User data storage program...");
    System.out.println("Please choose one of the following options:");
    System.out.println("");
    System.out.println("1. DATA INPUT ");
    DataManage object;
    object.FileCreate();
  }
}

import java.io.File;
import java.io.IOException;

public class DataManage  {
  public void FileCreate() {
    try {
      File file = new File("c:\\newfile.txt");
      if (file.createNewFile()) {
        System.out.println("File is created!");
      } else {
        System.out.println("File already exists.");
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Upvotes: 0

Views: 151

Answers (2)

Itzik Gili
Itzik Gili

Reputation: 324

In OOP programing , there are many kinds of classes you can use: You are lookin for creating new instance for a class - which means the class is dynamic.

There are two parts of "creating" a new instance to a class, First - the decleration (the type and the name of the instanse) You just did it by :

DataManage dataManage ;

now the other part is instatcing the new type we created using the "new" keyword:

DataManage dataManage = new DataManage();

By using the "new" keyword you call the constractor of DataManage (which is DataManage())

public void FileCreate()

Obviosly , the constactor can be built in a way it requires imputing parameters, so you will have to call the providing those parameters.

Then you can use the methods for the instance using the ".", just as you did before.

dataManage.FileCreate(); 

For classes that contain simple methods, called "Utility classes" you can use static classes, where you don't need to instantiate the class, and can simply call the methodes inside, But i advise you read this first , it will help avoiding common design mistakes and to maintain the OOP principles.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

You need to instantiate – that is, create an instance ofDataManage, before you can call a method on it. Everything else looks fine.

So where you currently have this:

DataManage object;

object.FileCreate();

use new to create a new instance:

DataManage object = new DataManage();

object.FileCreate();

Upvotes: 2

Related Questions