Events in Class Constructors
Hi All,
I would like to know if events (instance/static) can be raised within class constructors. My understanding is that events can be raised but not of the same class as the class constructor belongs to.
Please clarify.
Thanks and Regards,
Vidya.
Hi Vidya,
Welcome to SDN.
see this link
http://help.sap.com/saphelp_nw04/helpdata/en/41/7af4eca79e11d1950f0000e82de14a/content.htm
http://help.sap.com/saphelp_nw04/helpdata/en/0a/b552f7d30911d2b467006094192fe3/frameset.htm
http://help.sap.com/saphelp_nw04s/helpdata/en/41/7af4eca79e11d1950f0000e82de14a/frameset.htm
http://help.sap.com/saphelp_nw04/helpdata/en/08/d27c03b81011d194f60000e8353423/content.htm
for Implementing constructor outside class implementation..
use this code
codeREPORT zkarthik.
CLASS counter DEFINITION
CLASS counter DEFINITION.
PUBLIC SECTION.
*METHODS CONSTRUCTOR.
CLASS-METHODS: set IMPORTING value(set_value) TYPE i,
increment,
get EXPORTING value(get_value) TYPE i.
PRIVATE SECTION.
CLASS-DATA count TYPE i.
NO explicit constructor
*METHOD CONSTRUCTOR.
*WRITE:/ 'I AM CONSTRUCTOR DUDE'.
*ENDMETHOD.
ENDCLASS. "counter DEFINITION
CLASS counter IMPLEMENTATION
CLASS counter IMPLEMENTATION.
METHOD set.
count = set_value.
ENDMETHOD. "set
METHOD get.
ENDMETHOD. "get
METHOD increment.
ENDMETHOD. "increment
ENDCLASS. "counter IMPLEMENTATION
DATA cnt TYPE REF TO counter.
START-OF-SELECTION.
Implicit constructor is called
CREATE OBJECT cnt.
CALL METHOD counter=>set
EXPORTING
set_value = 5.
END-OF-SELECTION.[/code]
happy learning.
thanks
karthik
Similar Messages
-
Constructor and Class constructor
Hi all
Can any one explain me the functionality about Constructor and class constructor??
As well as normal methods, which you call using CALL METHOD, there are two special methods
called CONSTRUCTOR and CLASS_CONSTRUCTOR, which are automatically called when you
create an object (CONSTRUCTOR) or when you first access the components of a class
(CLASS_CONSTRUCTOR)
I have read the above mentioned document from SAP Documents but i found it bit difficult to understand can any one please help me on this??
Thanks and Regards,
Arun JosephHi,
Constructor
Implicitly, each class has an instance constructor method with the reserved name constructor and a static constructor method with the reserved name class_constructor.
The instance constructor is executed each time you create an object (instance) with the CREATE OBJECT statement, while the class constructor is executed exactly once before you first access a class.
The constructors are always present. However, to implement a constructor you must declare it explicitly with the METHODS or CLASS-METHODS statements. An instance constructor can have IMPORTING parameters and exceptions. You must pass all non-optional parameters when creating an object. Static constructors have no parameters.
Class Constructor
The static constructor is always called CLASS_CONSTRUCTER, and is called autmatically before the clas is first accessed, that is before any of the following actions are executed:
Creating an instance using CREATE_OBJECT
Adressing a static attribute using ->
Calling a ststic attribute using CALL METHOD
Registering a static event handler
Registering an evetm handler method for a static event
The static constructor cannot be called explicitly.
For better understanding check the following code:
REPORT z_constructor.
CLASS cl1 DEFINITION
CLASS cl1 DEFINITION.
PUBLIC SECTION.
METHODS:
add,
constructor IMPORTING v1 TYPE i
v2 TYPE i,
display.
CLASS-METHODS:
class_constructor.
PRIVATE SECTION.
DATA:
w_var1 TYPE i,
w_var2 TYPE i,
w_var3 TYPE i,
w_result TYPE i.
ENDCLASS. "cl1 DEFINITION
CLASS cl1 IMPLEMENTATION
CLASS cl1 IMPLEMENTATION.
METHOD constructor.
w_var1 = v1.
w_var2 = v2.
ENDMETHOD. "constructor
METHOD class_constructor.
WRITE:
/ 'Tihs is a class or static constructor.'.
ENDMETHOD. "class_constructor
METHOD add.
w_result = w_var1 + w_var2.
ENDMETHOD. "add
METHOD display.
WRITE:
/'The result is = ',w_result.
ENDMETHOD. "display
endclass.
" Main program----
data:
ref1 type ref to cl1.
parameters:
w_var1 type i,
w_var2 type i.
start-of-selection.
create object ref1 exporting v1 = w_var1
v2 = w_var2.
ref1->add( ).
ref1->d isplay( ).
Regards,
Anirban Bhattacharjee -
Creating a singleton Event Listener class
A typical singleton OO design pattern involved a protected (or private)
no-arg
constructor and a public instance() method that manages a private static
variable
referencing the single instance, internally invoking the no-arg constructor.
A class designated in web.xml as a <listener> must have a public no-arg
constructor.
(from http://e-docs.bea.com/wls/docs61/webapp/app_events.html#178593)
Anyone thoughts on how to accomplish both goals?
What I want to do: I'd like to set up a singleton to listen for session
events.
Other code will query this one-and-only-one session event listener for
various
information. Some of this info I can currently get from the runtime via
MBeans but
some I can't, hence my investigation into session event listeners.
TIA, matt.Hi Matt,
This sounds like a case where you will need to have two classes -- your
singleton class, and then your session event listener class, which would use
the singleton class.
Dennis Munsie
Developer Relations Engineer
BEA Support
"Matt Hembree" <[email protected]> wrote in message
news:[email protected]..
A typical singleton OO design pattern involved a protected (or private)
no-arg
constructor and a public instance() method that manages a private static
variable
referencing the single instance, internally invoking the no-argconstructor.
>
A class designated in web.xml as a <listener> must have a public no-arg
constructor.
(from http://e-docs.bea.com/wls/docs61/webapp/app_events.html#178593)
Anyone thoughts on how to accomplish both goals? -
How to inherit super class constructor in the sub class
I have a class A and class B
Class B extends Class A {
// if i use super i can access the super classs variables and methods
// But how to inherit super class constructor
}You cannot inherit constructors. You need to define all the ones you need in the subclass. You can then call the corresponding superclass constructor. e.g
public B() {
super();
public B(String name) {
super(name);
} -
More:Could u pls complete the following code by adding a class constructor?
Thank you for your concern about my post. Actually it is an exercise in book "Thinking in Java, 2nd edition, Revision 12" chapter 8. The exercise is described as below:
Create a class with an inner class that has a nondefault constructor. Create a second class with an inner class that inherits from the first inner class.
And I make some changes for the above exercise requiring the class which encloses the first inner class has a nondefault constructor.
There is something related to this topic in chapter 8 picked out for reference as below:
Inheriting from inner classes
Because the inner class constructor must attach to a reference of the enclosing class object, things are slightly complicated when you inherit from an inner class. The problem is that the �secret?reference to the enclosing class object must be initialized, and yet in the derived class there�s no longer a default object to attach to. The answer is to use a syntax provided to make the association explicit:
//: c08:InheritInner.java
// Inheriting an inner class.
class WithInner {
class Inner {}
public class InheritInner
extends WithInner.Inner {
//! InheritInner() {} // Won't compile
InheritInner(WithInner wi) {
wi.super();
public static void main(String[] args) {
WithInner wi = new WithInner();
InheritInner ii = new InheritInner(wi);
} ///:~
You can see that InheritInner is extending only the inner class, not the outer one. But when it comes time to create a constructor, the default one is no good and you can�t just pass a reference to an enclosing object. In addition, you must use the syntax
enclosingClassReference.super();
inside the constructor. This provides the necessary reference and the program will then compile.
My previous post is shown below, could you help me out?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Could you please help me complete the following code by generating
// the Test class constructor to ensure error free compilation? Please
// keep the constructor simple just to fulfill its basic functionality
// and leave the uncommented part untouched.
class Outer {
Outer (int i) {
System.out.println("Outer is " + i);
class Inner {
int i;
Inner (int i) {
this.i = i;
void prt () {
System.out.println("Inner is " + i);
public class Test extends Outer.Inner {
// Test Constructor
// is implemented
// here.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Test(Outer o, int i) {
o.super(i);
}Note that this doesn't quite answer the question from Thinking In Java, since your Test class is not an inner class (though there is no difference to the constructor requirements if you do make it an inner class). -
Set fields of derived class in base class constructor via reflection?
Does the Java Language Specification explicitly allow setting of fields of a derived class from within the base class' constructor via reflection? The following test case runs green, but I would really like to know if this Java code is compatible among different VM implementations.
Many thanks for your feedback!
Norman
public class DerivedClassReflectionWorksInBaseClassConstructorTest extends TestCase {
abstract static class A {
A() {
try {
getClass().getDeclaredField("x").setInt(this, 42);
} catch (Exception e) {
throw new RuntimeException(e);
static class B extends A {
int x;
B() {
B(int x) {
this.x = x;
public void testThatItWorks() {
assertEquals(42, new B().x);
assertEquals(99, new B(99).x);
}why not just put a method in the superclass that the subclasses can call to initialize the subclass member variable?In derived classes (which are plug-ins), clients can use a field annotation which provides some parameter metadata such as validators and the default value. The framework must set the default value of fields, before the class' initializer or constructors are called. If the framework would do this after derived class' initializer or constructors are called, they would be overwritten:
Framework:
public abstract class Operator {
public abstract void initialize();
}Plug-In:
public class SomeOperator extends Operator {
@Parameter(defaultValue="42", interval="[0,100)")
double threshold;
@Parameter(defaultValue="C", valueSet="A,B,C")
String mode;
public void setThreshold(double threshold) {this.threshold = threshold;}
public void setMode(String mode) {this.mode = mode;}
// called by the framework after default values have been set
public void initialize() {
}On the other hand, the default values and other metadata are also used to create GUIs and XML I/O for the derived operator class, without having it instantiated. So we cannot use the initial instance field values for that, because we don't have an instance. -
Is it possible to override super class constructor?
Is it possible to override super class constructor form subclass?
However, you can achieve do something that looks similar to overriding.
class Parent {
Parent(int i, String s) {
// do stuff
class Child extends Parent {
Child(int i, String s) {
super(i, s);
// do Child stuff here
new Parent(1, "abc");
new Child(2, "xyz");Although that's not overriding, it sort of looks similar. Is this what you were talking about? -
Reference to enclosing instance in inner class constructor
Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
class Outer {
class Inner extends Global {
public Inner(int x) {
// I want (Outer.this != null) here
super();
class Global {
public Global(int x) {class Outer {
class Inner extends Global {
public Inner(int x) {
// I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
inner class always has an implicit reference to an
instance of the enclosing class.Try this:
class Outer {
int m;
class Inner extends Global {
public Inner(int x) {
super(x);
protected void init(int x) {
xxx = Outer.this.m + x; // Null pointer exception!!!
class Global {
int xxx;
public Global(int x) {
init(x);
protected void init(int x) {
xxx = x; -
Events in classes LabVIEW 8.6
i have class with some member (counter of something)
and i want to generate a user event when this member has specific values.
currently i manage to generate the event only if i register the event of the class
in the Top Vi that use this class
can i register the event inside the class itself, let say inside the initilize vi that i ave for the this class ?
thanks
Solved!
Go to Solution.The question is a little confusing. You can register for the event anywhere you like, but somewhere you pretty much need to have an Event Structure in a running VI waiting for that event to occur.
What should be aware of these events? Class members
P.S. On second reading, it seems you might just be asking if you can register the event in a class VI, instead of having to register it in the top-level VI. If that's the case, then yes you can. Just have the Register for Events function inside the Initialize VI of your class and have it output the Event Registration Refnum corresponding to your event.
Message Edited by Jarrod S. on 11-02-2008 08:48 PM
Jarrod S.
National Instruments -
Class field initialization outside class constructor
Hi,
what are the benefits of initializing a class field outside the class constructor? I use this for fields, that i do not need to pass parameter to via the constructor. The code seems more clear/easy to read.Hi,
what are the benefits of initializing a class field
outside the class constructor? I use this for
fields, that i do not need to pass parameter to via
the constructor.
The code seems more clear/easy to read.That's a pretty big benefit.
For another, consider when you have multiple constructors: you've factored
common code out of them (good) and made it impossible to forget to
initialize that field later when, later on, you write another constructor(also good). -
Don't need call to super class constructor
Hi, I have
class A {
public A() { System.out.println("in A()");}
public class B extends A
{ public B() {
System.out.println("in B()");}
public static void main( String args[] ) {
B b = new B();}
I don't want the super class constructor to be called... What to do? Please tell me solution other than usage of parameterised constructor?I don't want the super class constructor to be called... What to do? Can't be done. One of the constructors of the super class must be invoked. (Implicitly or explicitly)
Kaj -
Can defualt inherited the Super Class constructor to sub class ?
Hi,
is it passible to inherit the super class constructor by defualt when extends the super class.
Thanks
MerlinRoshinaConstructor rules:
1) Every class has at least one ctor.
1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
1.3) Constructors are not inherited.
2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed. -
JTabbedPane single event handling class.
I have a list of proxyNames which are stored in a Vector.
These proxy names are then displayed as Tabs accordingly.
For every tab there is a specific action to be performed.
I want to write a single event handling class for handling all events.
What I have is this:
while(eNum.hasMoreElements()){
Object proxyName = eNum.nextElement();
tabbedPane.addTab(proxyName.toString(), null, null, "Proxy");
tabbedPane.addChangeListener(itemHandler);
panel4.add(tabbedPane2);
class ItemHandler implements ChangeListener{
public void stateChanged(ChangeEvent e){
for(int i=0; i < v.size(); i++){
// Perform action on choosing the concerned tab...
How do I have a single event listener?Yikes! Is that a minimal program? When I am trying to do something new, or facing a problem that causes me to get stuck for more than an hour, I create a short program to solve just that problem. In time, you create a directory of test programs that's useful, and with practice, solving a problem in isolation is a faster (and generally better) way to go about things that doing it all in a larger application.
Any way, here is your code, with a change listener added in method makeSubpanel. If you don't want the listener called the very first time, add it at the end of this method. I also fixed some bugs in createProxyList.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class TrialTabbed extends JPanel {
// Will hold all file names read from the /config directory.
private Vector v,v1;
JTabbedPane tabbedPane,tabbedPane2;
Object proxyName;
public TrialTabbed(){
tabbedPane = new JTabbedPane();
// Instantiate the Vector.
v1 = new Vector();
Component panel1 = makeTextPanel("Blah");
tabbedPane.addTab("Debug Mode", null, panel1, "Debug");
Component panel2 = makeSubPanel();
tabbedPane.addTab("Normal Mode", null, panel2, "Normal");
// Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));
add(tabbedPane);
protected Component makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
private Component makeSubPanel(){
JPanel panel4 = new JPanel(false);
panel4.setLayout(new GridLayout(1, 1));
tabbedPane2 = new JTabbedPane();
//new code - a change listener for pane2
tabbedPane2.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
int tab = tabbedPane2.getSelectedIndex();
if (tab == -1)
System.out.println("no tab selected");
else {
String filename = tabbedPane2.getTitleAt(tab);
File file = new File("..", filename); //brittle!
if (file.isDirectory()) {
String[] contents = file.list();
int size = contents == null ? 0 : contents.length;
System.out.println(filename + " contains " + size + " files");
} else
System.out.println(filename + " has length " + file.length());
//end of new code
ItemHandler itemHandler = new ItemHandler();
v = createProxyList();
// Enumerate thru the Vector and put them as tab names.
Enumeration eNum = v.elements();
while(eNum.hasMoreElements()){
proxyName = eNum.nextElement();
tabbedPane2.addTab(proxyName.toString(), null, null, "Proxy");
panel4.add(tabbedPane2);
return panel4;
// Display the file names in this directory as tab Names.
//new code: changed dirName to "..", fixed some obvious bugd
private Vector createProxyList(){
String dirName = "..";
File file = new File(dirName);
if(file.isDirectory()){
String[] s = file.list();
for(int i=0; i< s.length; i++){
v1.addElement(s);
} // End for.
} // End of if.
return v1;
} // End createProxyList().
class ItemHandler implements ChangeListener{
public void stateChanged(ChangeEvent e){
System.out.println(v.size());
System.out.println("IN CHANGE LISETENER" + proxyName.toString());
} // End actionPerformed.
} // End Inner class ItemHandler.
public static void main(String[] args) {
JFrame frame = new JFrame("TabbedPaneDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
frame.getContentPane().add(new TrialTabbed(),BorderLayout.CENTER);
frame.setSize(500, 425);
frame.setVisible(true); -
Calling Nested Class Constructor from main()
Consider the following code:
public class OuterClass {
static static void main(String[] args) {
NestedClass nc = new NestedClass()
class NestedClass {
NestedClass() {
//constructor logic here
}This call to the nested class constructor gives the following error: " 'OuterClass.this' cannot be referenced from a static context. However, if I cut and paste the code for NestedClass into its own class file, there are no error messages. I would like to be able to keep the class nested, so what do I need to do?static static void main(String[] args) {
NestedClass nc = new NestedClass()
}public static void main(String[] args) {
NestedClass nc = new NestedClass()
} -
Flash CS5 - code hinting doesn't show custom class constructor parameters
Hi I've got other strange problem my code hinting works almost fine the problem is that when I create my custom class object code hinting doesn't show what kind of parameters can be passed to the class constructor. It shows only "MyClass()", when i call a method like this class_object.methodName( - parameters show correctly. What can be the problem?
I do not work for Adobe, just a fellow forum dweller.
The example was made quickly because you said this:
I've tried flash builder but if there is a way to associate code directly from it to symbols on the timeline I haven't been able to find it.
Now you know how.
I'm sorry but I don't even have Flash CS6. I still use CS5.5 because I use Flash Builder 4.6 for everything I do. I merely use Flash Pro to generate quick libraries full of goodies and export a SWC to use in Flash Builder.
I realize it's obvious but you did ensure your preferences had hinting both enabled and the delay set low (or zero)? I can only show you a CS5.5 preference panel, I'm not sure if it's the same. Note one important thing in this photo which is "Cache size". I have mine on 800 files which seems to be fine. If you're pointing toward a HUGE library of classes you may want to increase that number and check completion again.
Maybe you are looking for
-
Windows 7 Pro 64 bit Expanding Windows FIles, reboots
Trying to do clean install of Windows 7 Pro 64 bit to Lenovo Thinkpad X140e laptop. I boot up the DVD, get to windows advanced install, add AMD AHCI driver from CD and start installation. Anywhere from 7% to 70% completion of the "Expanding Windows
-
How can I amke a full cold backup
Hi, I would like to make a full cold backup in command line mode and then recover it.How caI proceed? Backup sets or image copy? I have tried this but it didn't work, I made it after a normal dbstart. connected to target database: ISCREAM (DBID=34150
-
Programs/Applications/Sites won't connect to the internet
I just got my MacBook Air 13 with 10.8 Mountain Lion a few days ago, and I just did the basic set up. However, some of the programs/applications I downloaded are not able to connect to the internet. It seems like something is blocking their access. I
-
Hi, I have a requirement in which I have to change the notes added to the case notes section and interaction record (texts section). There is no option to change the previously entered notes when we try in change mode in CRM. Note: we are using CRM 5
-
Hi , I want to know what are the condition types involved for IMPORT PRICING PROCEDURE that i.e. we have to maintain from RFQ to P.O Please help me in detail about what are the condition types involved ? Thanks & Regards, Mani.