Goldengirl Goldengirl - 4 months ago 6
Java Question

How to call an entire class from another class in Java?

I am a beginner in Java. I have two packages in my current project. Each of the packages have two classes called the "packageClassOne" and "packageClassTwo".

The packageClassTwo has a constructor and other public methods.

I want to call the PackageClassTwo from an if statment located in the PackageClassOne. My code looks something like this

packageClassOne:

public class packageClassOne {
public void selectComponent(boolen) {
if(/* check condition*) {
packageClassTwo value = new packageClassTwo();
}
}
}


packageClassTwo:

public class packageClassTwo {

public packageClassTwo(String name){ //Constructor
int length = name.length();
}

public String CreateWord(){
/*functionality ofthis method*/
}

public String CreateSentence(){
/*functionality ofthis method*/
}
}


The problem is that everytime I call the packageClassTwo from my packageClassOne it tries to call the constructor instead of calling the class itself. I want to call the entire packageClassTwo instead of just the constructor.

Can somebody help me please? Thank you in advance for your help

Answer

Since Java is an object oriented language, you have to have a mindset of dealing with instances that are realizations of the classes you defined. These are the objects.

So if you want to call a method from packageClassTwo class, you first create an object of packageClassTwo. You seem to be trying to do just this. Once you have to object, you can call its methods. For example

//Initialize an object by calling the constructor
packageClassTwo object = new packageClassTwo(string);
//Now call its methods
String val = object.CreateWord()

There is no such thing as "calling a class". You call methods of objects of a class.

Occasionally, there might be a well founded need to call methods of a class without initializing objects. Look into static methods and classes for further reading.

Comments