How to call an entire class from another class in Java? - 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

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 the object, you can call its methods. For example
//Instantiate 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.

If you want to call all methods of packageClassTwo you have to do it explicitly
packageClassTwo pct = new packageClassTwo("");
pct.CreateWord();
pct.CreateSentence();
If you allways want the 2 methods to be called when you create a new packageClassTwo object, than you can just add the calls to the constructor
public packageClassTwo(String name) {
int length = name.length();
pct.CreateWord();
pct.CreateSentence();
}
Edit:
Note that in the second case, if you end up only calling the 2 methods from inside the constructor, it is better to make them private.
As a sidenote, it is a general convention in java to have class names start with a upper case letter : PackageClassTwo not packageClassTwo, and method names to start with lower case createWord not CreateWord. This wll make your code more readable.

If you want to call all the methods from the packageClassTwo, call them from the packageClassTwo constructor
public packageClassTwo(String name)
{
int length = name.length();
CreateWorld();
CreateSentence();
}

I don't think your code will run without compiling errors.because you did not declare the constructor packageClassTwo().

Related

Cannot Recognize the Syntax of this code(Which is Class, and which is Method)?

I have a problem with a code, which is I found an object linked to a class and this class calls a method and the method is trying to call another method? I know there is no nested method in Java.
But here is a sample of the code.
I tried to make the code as a class, class and a method but didn't work.
In the first file, we created an object of another class in another file.
private SnackMachine snackMachine;
The name of the class is "SnackMachine and snackMachine is the object.
in the use of the code.
assertThat(snackMachine.chewingGums().quantity()).isEqualTo(DEFAULT_QUANTITY);
as we see here object is calling a method, but after the method what is that?
and how can I replicate that?
I thought It's class inherited from another class and that has a method.
also I thought because it's we used the final keyword or static so we could call it with creating an object.
I assume DEFUALT_QUANTITY is a number, so quantity will have to return a number, that means it is a method.
I assume that First return an object and the second calls that object and invoke its the method.
In fact, the first method returns another object and so you can chain another call. The returned value is taken from the last call.
For example this (note the lack of semi-colons)
package com.github.francipvb.holamundo;
import java.util.*;
public class Main {
public static void main(String[] args) {
var sb = new StringBuilder()
// The append method returns the builder itself...
.append("str")
.append("another str")
.toString(); // this is the last call.
System.out.println(sb); // sb is a string
}
}

Accessing instance methods that are two objects deep in Java

Say I have a class, Bobject with an instance variable and method to retrieve it:
public class Bobject {
private int bInstVar;
public Bobject() {
bInstVar = 1;
}
getBInstVar() {
return bInstVar;
}
}
If I create a class Cobject representing an object that is an array of Bobject like so:
public class Cobject {
public Bobject[] cInstVar;
public Cobject() {
cInstVar = new Bobject[2]; //arbitrary array size for simplicity of the question
for (i = 0; i <= 2; i++;) {
cInstVar[i] = new Bobject();
}
}
}
If I have a main program that creates a Cobject and attempts to access methods of the references to the Bobjects stored in each element, I find that I have to first access the Cobject instance variable, cInstVar. This means cInstVar has to be public for main() to get at it without a method if main is outside of the package or class.
My question is, is there a way around doing this:?
Cobject c = new Cobject;
c.cObject1[0].getBInstVar();
Instead, I want to have an object that is an array of another class and get to that classes instance methods easier like so:
Cobject c = new Cobject;
c.getBInstVar(); // error says 'array required, but Cobject found'
I'm still pretty new to Java (and stackExchange) so please forgive me if anything I've presented is unclear. Thanks in advance!
As a general rule of thumb class variable should be declared as private and you should use getter and settle methods....
Meaning you will need to create a getter method in 'Cobject' to get the 'Bobject' object your after.... Then another getter/setter method to access any attributes there, or a method to manipulate any data
But yes, you could hard code a method that will go into the array and return what you ask for. Probably need an index parameter tho
you can create a getter method for Bobject[] in Cobject class
and then you can do c.getCObject1()[0].getBInstVar();

how to call method that contains array

Complete beginner here. I am trying to call a method from a class to run in the main class. But I cannot seem to figure out why it is not work. Here is how I am calling the class
public static void main(String[] args) {
findMP3Tracks FT = new findMP3Tracks();
FT.findMP3();
This is the class method i want to call
public static List<String> findMP3(String p)
{
List<String> foundMP3Tracks = new ArrayList<>();
try (DirectoryStream<Path> folderContents = Files.newDirectoryStream(Paths.get(p)))
{
//Look for
for (Path folderItem: folderContents){
if(Files.isDirectory(folderItem, LinkOption.NOFOLLOW_LINKS)) {
foundMP3Tracks.addAll(findMP3(folderItem.toString()));
}
else if(isValidMP3(folderItem.toString())) {
foundMP3Tracks.add(folderItem.toString());
}
}
}
Assuming findMP3(String) is a method inside the class findMP3Tracks (I would recommend you to follow Java conventions for class names), you may call it in the main as:
public static void main(String[] args) {
...
List<String> result = findMP3Tracks.findMP3("Name of MP3");
}
You may use the name of the class findMP3Tracks to invoke the method findMP3, because it is declared as static. So it's not necessary to create an instance to call it. (Of course you may want to create instances of that class for other operations)
Also, since findMP3 is returning a List<String>, you may want to store it in a variable (In the example result)
First, you don't need instances to call a static method, so this line
findMP3Tracks FT = new findMP3Tracks();
is useless, you can remove it.
Use (for example)
findMP3Tracks.findMP3("Some MP3 name");
Also you need to get the returned value, so it should be:
final List<String> mp3List = findMP3Tracks.findMP3("Some MP3 name");
PS: in Java by convention class names start with uppercase, I suggest you change findMP3Tracks class name to FindMP3Tracks
You've declared the method as
public static List<String> findMP3(String p)
which means (among other things) that when you call it, you're going to pass in a String argument. But you wrote
FT.findMP3();
where you're not passing in any argument at all. Something like
FT.findMP3("Hello");
would compile; or if you had a String variable whose value was the name of the MP3 that you wanted to search for, you could use that too. But the call to any method MUST match the declaration of that method.
The method findMP3 is declared as static. Static variables and methods are members of the class.
You can invoke it directly using the classname. So, it should be findMP3Tracks.findMP3()
Also, a word about the static method. If you do know that the behaviour of the method isnt different for different instances, then you might/can declare it as static. Although, it is a design decision that you would make. If it does behave differently based on the passed in parameter, it is better off to have a method which isnt static.

call get methods for different classes behind one another

I have a class with name "ConstituentSet". it has one method namely "getNucleusInConstSet()" which the output will be from "Proposition" class . The new Class "Proposition" have another method namely "getProperty()". I want to know what is the Propertry of my "Proposition Nucleus" in class "ConstituentSet". but i do not know how can i do that.
I wrote as follow but It does not work. (ConstituentSet.getNucleusInConstSet()).getProperty())
public class ConstituentSet{
// Constructor
private Proposition nucleusInConstSet;
public Proposition getNucleusInConstSet() {
return nucleusInConstSet;
}
}
public class Proposition{
//Constructor
private Property property;
public Property getProperty() {
return this.type;
}
}
You have:
(ConstituentSet.getNucleusInConstSet()).getProperty()
But you need to call an instance of ConstituentSet
e.g.
ConstituentSet cs = new ConstituentSet();
cs.getNucleusInConstSet().getProperty();
Note that this idiom (chained method calls) can be a pain. If one of your methods returns null, it's difficult to understand which one it is (without using a debugger). Note also that invocations of the form a().b().c().d() are a subtle form of broken encapsulation (a reveals that it has a b, that reveals it has a c etc.)
if you type ((ConstituentSet.getNucleusInConstSet()).getProperty()) you are attempting to call a static method of ConstituentSet.
You need to instantiate it and then call on that object.
ConstituentSet anInstanceOf = new ConstituentSet();
anInstanceOf.getNucleusInConstSet()).getProperty());
This won't work:
ConstituentSet.getNucleusInConstSet().getProperty();
Because the getNucleusInConstSet() method is not static. You have to use an instance of ConstituentSet, something like this:
ConstituentSet cs = new ConstituentSet();
cs.getNucleusInConstSet().getProperty();
Of course, you have to make sure that nucleusInConstSet is not null, or you'll get a NullPointerException. Initialize its value in ConstituentSet's constructor or set it using setNucleusInConstSet().
Alternatively, you could make getNucleusInConstSet() static, but I don't think that's the right thing to do in this case (but we don't have enough information about the problem to say so).

Non static method cannot be referenced from a static context for eeyore?

I have a class called ChristopherRobin (sub class of HundredAcreWoodsCharacter) in which there is a method called FindTail().
In another class, Eeyore (sub class of HundredAcreWoodsCharacter also), I want to try and use the method FindTail() from ChristopherRobin. I'm not sure how to do this. I tried
if (ChristopherRobin.hasTail())
but that gives me the error:
non-static method hasTail() cannot be referenced from a static context
If anyone could help it would be great, thanks.
Also, if it's worth mentioning that this is being done in GridWorld (from the AP Computer Science case study). HundredAcreWoodsCharacter is a subclass of Critter.
You're calling the non-static method on the class, something that can't be done. You need to first create a ChristopherRobin object and then call the method on the object.
// create the ChristopherRobin object and put in the christopherRobin variable
ChristopherRobin christopherRobin = new ChristopherRobin();
// now call the method on the *object* held by the variable
if (christopherRobin.hasTail()) {
// do something
}
You probably need to override the act() or, since this is a subclass of Critter, override one of the methods that act() calls. For instance, if having a tail affects how this Critter can move, then you would override getMoveLocations() Here's an example of how hasTail could be used:
//Critters with tails can only move forward.
public ArrayList<Location> getMoveLocations() {
if(this.hasTail()) {
ArrayList<Location> listOfOne = new ArrayList<Location>();
listOfOne.add(getLocation.getAdjacentLocation(this.getDirection()) );
return listOfOne;
}
else
return super.getMoveLocations();
}

Categories

Resources