I new to java so bear with me if this is a ridiculously simple question but I am curious about this method call which has {code} being taken in - see code below for an example in the method addSelectionListener. What is the purpose of this? I have been looking through docs for an explaination but cant seem to find what this practice is called never mind any useful information.
setStatusLine.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String message = "I would like to say hello to you.";
if (pressed) {
message = "Thank you for using me";
}
setStatusLine(message);
pressed = !pressed;
}
});
Thanks for any help or insights that can be offered
Constructor in java is used to create the instance of the class. Constructors are almost similar to methods except for two things - its name is the same as the class name and it has no return type. Sometimes constructors are also referred to as special methods to initialize an object.
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.
A constructor in Java is similar to a method that is invoked when an object of the class is created. Unlike Java methods, a constructor has the same name as that of the class and does not have any return type. For example, class Test { Test() { // constructor body } } Here, Test() is a constructor.
Language constructs are part of a program that is formed from a combination of one or more tokens which syntactically acceptable and are as per specified rules of programming language.
this is an Anonymous Class, or Anonymous inner class. If you google for that you will find some tutorials/examples. Sun has some docs too.
As the other contributors already said: It is an Anonymous Class
You could have created a new class named MyClass in a new file called McClass.java looking like that:
class MyClass extends SelectionAdapter {
public void widgetSelected(SelectionEvent e) {
<your code that's being executed whenever the widget is being selected>
}
}
Then you could have changed the first line like that:
setStatusLine.addSelectionListener(new MyClass());
See? Now you have an "explicit" class with just one function. Often that is too much overhead and would clutter your design.
Does that help?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With