Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have met the text "doSomethind() method is modiffied to trail another method", and it is not very clear to me what does this means?
Does it means that it is calling the "another method"?
Does it means it is overwriting or overridding the "another method"?
Does it means that it is called by the "another method"?
I am really confused.
"Method trailing" is not a defined term in Computer Science or Java. It appears that the person who wrote this text is using their own private terminology. You should ask them to find out.
My personal speculation would conclude in that:
The author means that the method is placed before another method in the source code; or
The author is refering to Method chaining
"If doSomethings(), that has no exception handling code, trails a method that throws an exception, what will make the code to compile?"
"Trails" could mean anything. I would have assumed it just means it appears after another method in the class file, but I assume the author had something else in mind.
"no exception handling code" This doesn't imply anything at all. In the code below, there is no exception handling code and it compiles fine.
There is nothing in the quote which suggests you need to do anything special to write a method which compiles.
Warning: some web sites (rose india comes to mind) have lots of written material which is technically confused and shouldn't be read too closely, if at all. They are like a lot of marketing, nice on the surface, but the more you think about them, the less sense they make ;)
Say you have code like this
public void a() {
b();
}
public void b() {
c();
}
Does it means that it is calling the "another method"?
Method b is calling another method named c
Does it means it is overwriting or overridding the "another method"?
Overriding means it overrides a method defining in a parent class instead of inheriting it.
Overwriting is something you can do to a file, but not a method.
Does it means that it is called by the "another method"?
Method b is called by another method nameda
It looks like a case of Method Chaining:
public class SomeClass {
public SomeClass method1() {
// code here
return this;
}
public SomeClass method2() {
// code here
return this;
}
}
Usage:
SomeClass someObj = new SomeClass();
someObj.method1().method2();
This pattern is a somewhat niche one but it appears in many places (like Query frameworks) or used together with other patterns (like the Builder pattern).
There is no overriding/overloading in either case and they are not calling each other either.
Related
I have a plan to make a GUI as minimal as it gets. I have hit a brick wall where I cant find an answer or maybe some kind of workaround due to me being inexperienced in java.
I have searched quite a bit and only found ways to replace the last letter or number in a string but not in a method call
public static int question;
public static void main(String[] args) {
int questionNumber = Integer.parseInt(JOptionPane.showInputDialog("Enter project no."));
if (questionNumber>=7){
questionNumber=6;
}
else if(questionNumber<=3){
questionNumber=4;
}
question = questionNumber;
System.out.println(question);
System.out.println(questionNumber);
for(int i=4; i<=6;i++)
if(question==i){
Question4(); // want the number 4 to be the question variable
}
}
What I would expect is
for(int i=4; i<=6;i++)
if(question==i){
Question *the variable "question" here* ();
}
and have no idea if that is possible or how to get there.
Is it possible to reference different methods with one method call in
a for loop?
Yes. It depends upon what exactly you mean by different methods. Here are three general ways in which this can be achieved:
The Java enum facility allows developers to define constant-specific methods, which are different method bodies defined in each separate enum constant declaration. The actual method body that is invoked depends upon the actual enum constant upon which the method call is made (this is actually a specialization of the next bullet item).
Interfaces enable different method bodies to be defined in each separate implementation. In this way, the actual method body that is invoked depends on the instance of the actual implementation upon which the method call is made.
Another way to invoke different method bodies with "the same method call" is to perform method invocations using Java's Reflection Facility. Since Java is an Object-oriented development environment, a decision to use reflection should be made carefully. Reflection is (often much) slower, less readable, and clumsier than solutions that don't use it. Reflection also makes many errors which could be detected at compile-time detectable at run-time only.
In Java, the principle mechanisms of abstraction are classes and interfaces and, so, when thinking about a problem domain and resolving that into an object domain you should be thinking about how to design interfaces and classes that provide the most natural description possible.
You want to be able to invoke a method that corresponds to a particular question. A better way to approach this is not to abstract over it with the method call to a question, but to abstract over the questions themselves. Your project has questions, so this is a good clue that you should have a Question class.
Here is a skeletal solution to the problem that makes use of the Java enum facility (enums are a special kind of class). This solution is similar to the one suggested by Matthieu but it does not need reflection at all; instead it uses the first bullet item above and defines constant-specific methods (which is, itself, a specialization of the second bullet item above):
public enum Question {
QUESTION_1 {
#Override public String getText() {
return "This is the text for Question #1.";
}
},
QUESTION_2 {
#Override public String getText() {
return "This is the text for Question #2.";
}
},
:
:
QUESTION_N {
#Override public String getText() {
return "This is the text for the final question in the series.";
}
};
public abstract String getText();
}
This enum class defines one constant for each question in the series of questions (each of these constant declarations becomes an instance of the enum class Question at run-time). Each declaration defines a different method body for the method getText() which is overridden inside each enum constant.
The declaration public abstract... at the end of the enum informs the compiler that every enum constant must provide an implementation for the getText() method. If a developer adds a new question to the series but forgets to add a getText() method in it, the compiler will complain (this is a type of error that can be caught at compile-time with an object-based solution that could only be caught at run-time if reflection were used).
Here is a simple program to exercise your Question enum class. It simply prints out the name of each question constant followed by its question text:
public static void main(String[] args) {
for (Question question : Question.values()) { // here is the "one for loop"
String text = question.getText(); // here is the "one method call"
println(question.toString());
println(text);
}
}
No reflection is used. Instead, natural abstraction mechanisms of Java's type system are able to achieve the desired goal of invoking a separate method body for each question.
Using map in this situation is most easiest solution. You should learn how to use them and how they works but, this is more about design now. If you want pass some parameters into your method take a look on Consumer, BiConsumer or even Function class provided by java. Check this example how it could implementation looks with Runnable that takes no parameters.
Map<Integer, Runnable> map = new HashMap<>(); // creating Map variable
// registering questions
map.put(1, () -> {
System.out.println("Question #1");
});
int questionNumber = 0;// get option id
if (map.containsKey(questionNumber)) { // first check if question is registered
map.get(questionNumber).run(); // get runnable that is registered with exact questionNumber and run it
} else {
// print invalid question number
}
You can use reflection:
try {
Method m = MyClass.class.getDeclaredMethod("Question"+questionNum);
m.invoke(this);
} catch (NoSuchMethodException e) {
// Handle
}
But you should handle the exception properly, because it will most probably fail one day or another.
You can also use an enum to define each behavior and call the appropriate:
private static enum EnQuestion {
Question1 {
public void run(MyClass instance) {
// ...
}
},
Question2 {
...
},
...
QuestionN {
...
};
public void run(MyClass instance);
}
The enum has to be static so you can't access MyClass protected/private fields and methods.
Then call it:
EnQuestion.values()[numQuestion].run(this);
This question already has answers here:
How do I find the caller of a method using stacktrace or reflection?
(13 answers)
Closed 9 years ago.
Just wondering, how do you find out the name of the method that invokes another method? I want to use the Method class.
You can make use of StackTraceElement :
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
Order of elements in StackTraceElement array: The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence.
Once you have the desired method name then you can call it using reflection :
Method lastMethod = YourClass.class.getMethod("yourMethodName");
lastMethod.invoke();
Note: The code should be changed as per your class and method.
Getting the name is tricky enough, getting the method is very hard because you don't know the argument list but you do know the class and you can use the line number when reading the byte code to find which method which contains that line. If the method is static (and I suspect its not) you are ok. If you need an instance, finding that is next to impossible in any portable way.
The sort of thing you are trying to do is the Java equivalent of saying; how do I learn to flight in a couple of easy steps.
What ever your problem is this is highly unlikely to be a good solution. If you need to call back to the object which called you, you should pass that object as an argument, ideally via an interface.
When ever you find the code running back on itself, this is sure to end in a mess of some kind, You want to simplify your dependencies.
What you should do is something like this.
interface Callback<T> {
onResult(T t);
}
class A implements Callback<MyResult> {
B b = new B();
public void method() {
b.doSomething(this);
}
public void onResult(MyResult mr) {
// do something with mr
}
}
class B {
public void doSomething(Callback<MyResult> cb) {
// do something
cb.onResult(new MyResult(something));
// do something else
}
}
Of course this would be all much simpler if instead of call back on the first method, you just returned a result and half this code wouldn't be needed. This is why normally when you want to pass something back to the caller, you use a return value instead of recursion.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
the first example is possible, but example 2 is not possible and results in "illegal start of expression" error message from the compiler. why is it not possible to define a method inside of the run() method?
example 1
public class TextUpdater implements Runnable {
public void inter(){
}
#Override
public void run() {
inter();
}
}
}
example 2, not possible
public class TextUpdater implements Runnable {
#Override
public void run() {
public void inter(){ // results in error
}
}
}
Java does not let you define a method inside a method. It doesn't even have any semantic rules for what that would do. What are you expecting example 2 to do?
It's clear what example 1 does. You create a method called inter with an empty body. Then, in run, you call it.
But what should 2 do? You create a method inter inside run. So what would that do? When would you call it?
If you actually declare a method within a method it will always result in an error. Java is strictly object-oriented and it requires methods to belong to a class. In other words, you have to declare your methods in class. JavaScript, Python and other object-oriented languages loosen this strict rule, but Java does not. Read this thread on stackoverflow. It is almost exactly the same topic.
Because you cannot define a method inside a method.
Not possible to create a method inside another method.
run() is a method, you just can not define new methods inside a method.
Methods are defining in class section not inside methods
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I understand what is java method invocation and have practiced many examples using it.
I want to know what is the practical situation or need of this concept.
It would be of great help if anyone could give a real world scenario where it is used and
what would happen if this concept would have not been there?
Here is an example. Suppose we have 2 classes:
class A {
public String getName() {
return "A";
}
}
class B extends A {
public String getName() {
return "B";
}
}
If we now do the following:
public static void main(String[] args) {
A myA = new B();
System.out.println(myA.getName());
}
we get the result
B
If Java didn't have virtual method invocation, it would determine at compile time that the getName() to be called is the one that belongs to the A class. Since it doesn't, but determines this at runtime depending on the actual class that myA points to, we get the above result.
[EDIT to add (slightly contrived) example]
You could use this feature to write a method that takes any number of Objects as argument and prints them like this:
public void printObjects(Object... objects) {
for (Object o: objects) {
System.out.println(o.toString());
}
}
This will work for any mix of Objects. If Java didn't have virtual method invocation, all Objects would be printed using Object´s toString() which isn't very readable. Now instead, the toString() of each actual class will be used, meaning that the printout will usually be much more readable.
OK, I'll try to provide a simple example. You are writing a method that will fill a caller-supplied list:
public void fill(List l) {
list.add("I just filled the list!");
}
Now, one caller wants to use a linked list; another one prefers a list implementation based on an array. There will be other callers with even more list implementations that you've never even heard of. These are totally different objects. Propose a solution that achieves this without relying on virtual methods.
Without virtual methods this would mean that the type List would already need to have the method add implemented. Even if you had a subtype ArrayList which had an overridden method, the compiler (and the runtime!) would simply ignore that method and use the one in List. It would be impossible to use different List implementations that conform to the same interface; it would be impossible to reuse that line of code in the method fill since it would work only with the method in the type List.
So you see, the whole idea of type hierarchy wouldn't make a lot of sense; interfaces and abstract classes couldn't even exist. The whole of Java would break down into shards without that one feature of virtual methods.
In a recent question, someone asked about static methods and one of the answers stated that you generally call them with something like:
MyClassName.myStaticMethod();
The comments on that also stated that you could also call it via an object with:
MyClassName myVar;
myVar.myStaticMethod();
but that it was considered bad form.
Now it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not (a).
Is there some problem with calling static functions via an object? Obviously you wouldn't want to create a brand new object just to call it:
Integer xyzzy;
int plugh = xyzzy.parseInt ("42", 10);
But, if you already have an object of the desired type, is there a problem in using it?
(a) Obviously, I can't call a non-static method with:
MyClassName.myNonStaticMethod();
but that's not the issue I'm asking about here.
In my opinion, the real use case that makes this so unreadable is something like this. What does the code below print?
//in a main method somewhere
Super instance = new Sub();
instance.method();
//...
public class Super {
public static void method() {
System.out.println("Super");
}
}
public class Sub extends Super {
public static void method() {
System.out.println("Sub");
}
}
The answer is that it prints "Super", because static methods are not virtual. Even though instance is-a Sub, the compiler can only go on the type of the variable which is Super. However, by calling the method via instance rather than Super, you are subtly implying that it will be virtual.
In fact, a developer reading the instance.method() would have to look at the declaration of the method (its signature) to know which method it actually being called. You mention
it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not
But in the case above context is actually very important!
I can fairly confidently say it was a mistake for the language designers to allow this in the first place. Stay away.
The bad form comment comes from the Coding Conventions for Java
See http://www.oracle.com/technetwork/java/codeconventions-137265.html#587
The reason for it, if you think about it, is that the method, being static, does not belong to any particular object. Because it belongs to the class, why would you want to elevate a particular object to such a special status that it appears to own a method?
In your particular example, you can use an existing integer through which to call parseInt (that is, it is legal in Java) but that puts the reader's focus on that particular integer object. It can be confusing to readers, and therefore the guidance is to avoid this style.
Regarding this making life easier for you the programmer, turn it around and ask what makes life easier on the reader? There are two kinds of methods: instance and static. When you see a the expression C.m and you know C is a class, you know m must be a static method. When you see x.m (where x is an instance) you can't tell, but it looks like an instance method and so most everyone reserves this syntax for instance methods only.
It's a matter of communication. Calling a method on an instance implies you're acting on/with that particular instance, not on/with the instance's class.
It might get super confusing when you have an object that inherits from another object, overriding its static method. Especially if you're referring to the object as a type of its ancestor class. It wouldn't be obvious as to which method you're running.