What I am trying to do is set a value in a variable contained within another class.
this is how I am currently trying to achieve it.
BookingUI Class
private void setCarRegNo()
{
aBooking.setCarRegNo();
}
Booking class
public void setCarRegNo(String regNo)
{
carRegNo = regNo;
}
Yet I keep getting an error saying 'setCarRegNo (java.lang.String) in booking cannot be applied to ()
What is it I am doing wrong? Many thanks
You need to pass a String into the setCarRegNo(String ) of Booking class. The method signature declares that it requires a String argument, and your compiler will complain if you dont supply one.
You have to pass a string into the setCarRegNo() function.
Like this: setCarRegNo("Some string");
In your Booking Class, setCarRegNo takes a single parameter of type String.
When you call it from BookingUI, you are not passing in any parameters.
You need to change BookingUI to something like:
private void setCarRegNo()
{
aBooking.setCarRegNo("CarRegNo");
}
you need to pass a string to your setter. change
aBooking.setCarRegNo();
to
aBooking.setCarRegNo("the registration number');
as a note, you should fully spell out the words of the variables.
Related
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().
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.
Is there a way, using Java Reflection or otherwise, by which a method can retrieve its own name? Preferably as a string.
Context:- I have a method, which calls another method which would take as input the name of the first method. So I need a way for the first method to be aware of its own name..
Example:-
public class Example
{
static void exampleMethod1()
{
exampleMethod2(name_of_exampleMethod1);
}
static void exampleMethod2(String value)
{
-------some code------------
}
}
As an alternative, you can get it from the current stack:
System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName())
What you ask for can be done by analyzing the stack trace:
new Throwable().getStackTrace()[0].getMethodName();
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).
I'm trying to solve the following issue in reflection. I've a POJO which kind of acts as a metadata for the method signature in TestResponse class. TestResponse has a setDate() methid which takes a Date parameter. I'm trying to make this is a generic code which can accept any method and its signature to set in the response. What I'm not able to figure out is how to set the parameter Class while calling getMethod() based on the input. The input tells me to set the parameter as Date, but not sure how to achiever that.
Here's my sample code. Ofcourse, the mdi.modifier.getClass() is wrong since it'll get String.class instead of Date.class.
TestResponse response = new TestResponse();
Object val = "test";
MDIBase mdi = new MDIBase("setDate", "Date");
Method m = response.getClass().getMethod(mdi.method, mdi.modifier.getClass());
m.invoke(response, new Object[] { val });
Here's MDIBase
public class MDIBase {
public String method;
public String modifier;
public MDIBase(String method, String modifier){
this.method = method;
this.modifier = modifier;
}
Any pointers will be highly appreciated.
Thanks
I'm not sure I fully understand you, but if I do, you want to be able to pass in a class name for the parameter?
In order to do that, instead of passing in "Date" pass in "java.util.Date" (this is known as the fully qualified class name) and then instead of getClass call
response.getClass().getMethod(mdi.method, Class.forName(mdi.modifier));
That will dynamically load the class that has the fully qualified name you supplied.
Is that what you're looking for? If not, give me some more information and I'll take another stab at it.