Click here to Skip to main content
15,881,729 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I know how to create a method:

Java
public/private static/none dataType/void methodName(arguments) {
/*
 * Code in here
 */
}


I was wondering, if I used this:

Java
public static void setStat() {

}


I could have a method that branches off of
Java
public static void setStat() {

}


like so:

Java
Class.setStat().attack(5);


If this is possible, how would I do it?? Could you give me a code example??

EDIT:

I also want to do this:

Java
Class.addStat().attack(5);


So that I can either add or set the stat. I am also confused on what to return in

Java
public static void setStat() {

}


Please provide an example and not just an explanation. I learn from examples so that I know what I'm looking for.

What I have tried:

I have tried looking on google, but all their tutorials seem way too complex and take up lots of time.
Posted
Updated 6-Dec-16 20:12pm
v2
Comments
Peter Leow 5-Dec-16 23:06pm    
The closest you can get is the new lambda expressions included in Java Platform Standard Edition. Read http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html

Java
public static void setStat() {
 
}

Class.setStat().attack(5);

No that will not work, because setStat does not return anything. In order to call a sub-method setStat needs to return an object reference.
 
Share this answer
 
Comments
CPallini 6-Dec-16 4:01am    
5.
NickTheDev 6-Dec-16 21:48pm    
So, what would I return? Also, is there a way of checking if the method was referenced again, that it would not allow me to use it? Example:


Class.setStat().setStat().setStat();

I don't want ^^^ to happen. I want to be allowed to reference it once, and not be able to reference it over and over again. Also, what would I do with the attack method? Do I have to somehow make a reference back to setStat() or simply return the value I set as the attack?
Richard MacCutchan 7-Dec-16 3:50am    
I already said in my answer, it needs to return an object reference. You can only call a method on a class name for static methods, or an object reference for ordinary methods. In your example above, setStat must return a reference to an object of the class that contains a method named attack.


If you do not understand the basics of the Java language you are not going to get very far. I suggest you go to Lesson: Classes and Objects (The Java™ Tutorials > Learning the Java Language)[^] and study it in detail.
That's called method chaining, and must use the technique suggested by Richard. See, for instance: how to achieve method chaining in java? - Stack Overflow[^].
 
Share this answer
 
public static void disp(){

}
class.disp(5);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900