Implementing constructor outside class implementation..

REPORT  ZTUSH.
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.
ENDCLASS.
METHOD CONSTRUCTOR.
WRITE:/ 'I AM CONSTRUCTOR DUDE'.
ENDMETHOD.
CLASS counter IMPLEMENTATION.
METHOD set.
    count = set_value.
  ENDMETHOD.
ENDCLASS.
DATA cnt TYPE REF TO counter.
START-OF-SELECTION.
  CREATE OBJECT cnt.
  CALL METHOD counter=>set EXPORTING set_value = number.
I THOUGHT WE CAN DEFINE CONSTRUCTOR METHOD OUTSIDE CLASS IMPLEMENTATION AS IN JAVA. But when I do that I get an error, method can be implemented only withing class. Why?

Hello Rajesh
I do not fully understand what you mean by "I THOUGHT WE CAN DEFINE CONSTRUCTOR METHOD OUTSIDE CLASS IMPLEMENTATION AS IN JAVA". However, if you mean that we can create an object without having an explicit CONSTRUCTOR method defined then this is possible in ABAP like in Java (see coding below).
Regards
  Uwe
REPORT ztush.
*       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.

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 Joseph

    Hi,
    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

  • Error getting Constructor[] from class.getConstructors()

    Hi,
    I am trying to use java.lang.reflect package as under:
    import java.lang.reflect.*;
    import java.lang.reflect.Constructor;
    public class reflects1
    public reflects1(String str) {
         System.out.println("string constructor");
    public static void main(String args[])
    String name = args[0];
    System.out.println("classname is:" + name);
    try {
    Class cls = Class.forName("reflects1");
         Class[] param1 = {String.class};
    Constructor const = cls.getConstructor(param1);
         } catch (Exception ex) {}
    I always get following two compilation errors:
    1) Invalid Expression Statement: Constructor[] const = cls.getConstructor(param1);
    2) ; expected, Constructor[] const = cls.getConstructor(param1);
    Please let me know if you see any problem with this statement.
    Thanks.

    You seem to be mixing getConstructor and getConstructors, which are two separate methods, only the latter returns an array.

  • 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).

  • JAXB: How to have my generated classes subclass some other outside class ?

    With my XJS and DTD, JAXB generates the following:
    public class FraisMessage
        extends MarshallableRootElement
        implements RootElement
    { etc...I would like it to generate this instead:
    public class FraisMessage extends MyOtherClass
        extends MarshallableRootElement
        implements RootElement
    { etc...MyOtherClass is another class outside the scope of JAXB
    How do I do this ? What do I have to put in my XJS to get this ?

    You cannot do that. TheJAVA language does not allow a class to "extend" more than one upper class.
    Typically, the solution is to modify your architecture a little bit. Just use the "has a" relationship instead of "is a". That means something like that:public class MyFraisMessage
        extends MyOtherClass
        private FraisMessage message;
      etc...You write an extension "MyFraisMessage" of your upper class "MyOtherClass", which has the JAXB generated object as an attribute. This structure is often useful, when you think you would need multiple inheritance.

  • Method in a class that should not be visible to outside class

    I am using Spring task executor and I have a service that has two method.
    public SpringTaskExecutor implement SpringExecutor {
    List<Info> infos;
    //called by spring to poll the db after every 10 mts
    public pollDatabaseAfterEveryTenMinute(){
    .infos= new ArrayList<Info>();
    infos.add....
    //called by other class to get polling details
    public List<Infor> getInfoOfTeam(){
    return infos;
    But I want to make pollDatabaseAfterEveryTenMinute as private or protected so that only Spring can call it ,but no one else.
    Unfortunately I cannot make it private/protected because I implement an interface and spring will not find if I dont define the method in the interface.The second alternative is not to implement the interface.
    Please tell me if I have any other alternative

    You can't. There is no syntax for 'only Spring can call this method'. Spring has defined the method in an interface, so it is public, so anybody can call it.

  • Determine a string from main class in an outside class

    Hello there,
    This might be stupid question but I cant think, I am so very tired. Okay here is the question, is there any way we could see or the get the value of a string(just a string which is set in main class'A', its already set, we cannot make it static r anything like that)in a method outside that main class, probably in a method 'x' in class'C'.
    Thanks
    potti

    Yes, you can, in many ways, or else Java would be moot. Excluding the static way of doing it, which by the way is evil, your class C can make an instance of class A and then access it either as a public field or as the value returned by a public method. You can also use inheritance, but it's pointless in this case, inheritance is meant to abstract, extend functionality, and prevent having to rewrite code. It's not meant for accessing fields. And by the way, inheritance, too, is evil.
    This is one way to do it.
    class A {
         public String s = "great balls of fire";
    public class C {
         public static void main(String[] args) {
              A myInstance = new A();
              String s = myInstance.s;
              System.out.println(s);
    }This is the preferred way to do it, as it encapsulates the String. The idea of encapsulation is to access fields by a method instead of directly since interfaces are less likely to change than an object's data and in the case that the object's data does change and the interface does not, the changes will remain local.
    class A {
         private String s = "great balls of fire";
         public String getS() { return s; }
    public class C {
         public static void main(String[] args) {
              A a = new A();
              String s = a.getS();
              System.out.println(s);
    }

  • Constructor of class A instantiating class B and vice versa

    Hi folks,
    I have two classes, namely ZCL_EMPLOYEE and ZCL_USER.
    ZCL_EMPLOYEE has an attribute USER type ref to ZCL_USER, populated by a "create object" statement in the constructor method.
    ZCL_USER has an attribute EMPLOYEE type ref to ZCL_EMPLOYEE, also populated by a "create object" statement in the constructor method.
    Thus when I instantiate one of the classes, this inevitably results in an endless loop.
    Is there any way to avoid this? I guess it must be possible to catch already instanciated objects and re-use them rather than instantiating all the time, but how?
    Thanks a lot for your help,
    Patrick

    Hello Patrick
    Since you need to create a couple of instance at the same time this is a task I would solve with the FACTORY pattern, e.g.:
    Both class contain static factory methods and the instantiation is set private as suggested by Matthew, e.g.:
    DATA:
      lo_user     TYPE REF TO zcl_user,
      lo_empl    TYPE REF TO zcl_employee.
      lo_user = zcl_user=>create( id_uname = <username> ).
      lo_empl = zcl_employee=>create( id_pernr = <personnel number> ).
    CREATE method of ZCL_USER:
    METHOD create. 
      CREATE OBJECT ro_instance    " of TYPE REF zcl_user
        EXPORTING
          id_uname = id_uname
    *      io_employee =                     " optional parameter for employee instance      
    ENDMETHOD.
    CREATE method of ZCL_EMPLOYEE:
    METHOD create.
      CREATE OBJECT ro_instance    " of TYPE REF zcl_employee
        EXPORTING
          id_pernr = id_pernr
    *      io_user  =                            " optional parameter for user instance
    ENDMETHOD.
    CONSTRUCTOR method of ZCL_USER:
    METHOD constructor.
      IF ( io_employee IS BOUND ).
        me->mo_employee = io_employee.
      ELSE.
        " get PERNR via infotype 0105
        CREATE OBJECT me->mo_employee
          EXPORTING
            id_pernr = <personnel number>
            io_user  = me.
      ENDIF.
    ENDMETHOD.
    CONSTRUCTOR method of ZCL_EMPLOYEE:
    METHOD constructor.
      IF ( io_user IS BOUND ).
        me->mo_user = io_user.
      ELSE.
        " get uname via infotype 0105
        CREATE OBJECT me->mo_user
          EXPORTING
            id_uname = <username>
            io_employee  = me.
      ENDIF.
    ENDMETHOD.
    Final remark: If you are not yet aware of class CL_PT_EMPLOYEE you may want to have a look at my Wiki posting
    [Unified Access to All HR Infotypes|https://wiki.sdn.sap.com/wiki/display/Snippets/UnifiedAccesstoAllHR+Infotypes]
    Regards
      Uwe

  • ToString() overrides in constructor-less classes? [CS3,JS]

    How do I override the toString() method in a class that lacks its own constructor?
    (I'm actually working with the ManagedArticle class from Woodwing's SmartConnection plugin, but the probem appears to be general for any such class, so here we are with Page).
    Example:
    Page.prototype.toString = function() {
         return "[object Page "+this.name+"]";
    p0 = app.activeDocument.pages[0];
    $.writeln("1: "+p0);
    $.writeln("2: "+p0.toString());
    $.writeln("3: "+Page.prototype.toString.call(p0));
    p1 = app.activeDocument.pages.add();
    $.writeln("4: "+p1);
    $.writeln("5: "+p1.toString());
    $.writeln("6: "+Page.prototype.toString.call(p1));
    produces:
    1: [object Page]
    2: [object Page]
    3: [object Page 1]
    4: [object Page]
    5: [object Page]
    6: [object Page 2]
    Is this a fool's errand? I'd really like easier debugging of this class and overriding the toString() would seem to be the way-to-go.
    Thanks!

    You actually can do it to InDesign DOM objects (well some of them -- in certain ways anyhow). Here's a particularly interesting one:
    var itemByLabel = function (label){
        var labelIndex = null;
        var labelArray = this.everyItem().label;
        for(var i=0;i<labelArray.length;i++){
            if(labelArray[i]==label){labelIndex = i;break}
        if(labelIndex===null){return null}
        return this.item(labelIndex);
    app.documents[0].pageItems;//needed to initialize the PageItems object
    PageItems.prototype.itemByLabel = itemByLabel;
    app.documents[0].paragraphStyles;//needed to initialize the ParagraphStyles object
    ParagraphStyles.prototype.itemByLabel = itemByLabel;
    etc...
    I am very wary of prototyping anything but the simplest JS objects though...
    You can do it with a regular function or method in a custom library (like Bob likes to do).
    function CustomToString(object){
         var string = object.toString();
         string+="bla bla bla";
         return string;
    Harbs

  • Find classes in ear from a outside class

    How can we find classes located in a ear from a class that is located outside the
    archive? Is it possible?
    Regards
    Nick

    Well, the purpose of an ear file is to bundle your entire application into one
    file.
    If you have a class B that needs to use class A which just happens to be in your
    ear file, I would think that this file resides in a completely different Application
    on the server.
    If that's the case, then you definitely need to place class A which is in your
    ear file into the classpath of the application which contains class B, or into
    the same ear file of class B's application.
    If not and both are part of the same application, then why isn't class B included
    in the ear file to begin with?
    Hope this helps..
    "Nick" <[email protected]> wrote:
    >
    How can we find classes located in a ear from a class that is located
    outside the
    archive? Is it possible?
    Regards
    Nick

  • How to use outside Class in packed library plugins

    I have found the very useful article from Michael Lacasse (https://decibel.ni.com/content/docs/DOC-19176) on how to use packed library as plugins. This approach makes the most sense when you try to distribute additional code after your executable has already been installed.
    My problem is that when I try to use a class from the main code in a plugin, the plugins won't work anymore. Ideally, I would have liked the parent plugin-interface to inherit from a class used in the main code, or using the class as an input parameter of the plugin would be the next best thing.
    I got several errors, some at execution time (#1448) or at edit time ("This VI does not match other VIs in the method: connector pane terminal(s)"). I have settled to use clusters to pass data to the plugins.
    My question is: Is it possible to use a class defined in the main code in a packed-project-library, either inherited or as a parameter? If yes, do you have any example?
    Marc Dubois
    HaroTek LLC
    www.harotek.com
    Solved!
    Go to Solution.

    I should point out that it's important to use the copy THAT'S IN THE PPL, *-NOT-* the copy from your source.
    It will compile if you mix them together, but they aren't the same object, and won't share data.
    You should never refer to your source code for the class, except to build the PPL.
    (Consider using a separate project, to avoid temptation).
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • NoClassDefFoundError when accessing outside class

    In my iView I need to reference to a class from a different package. I get NoClassDefFoundError exception trying it.
    I have a SharingReference for that package in my portalapp.xml:
    <application-config>
    <property name="SharingReference" value="myPackage.common" />
    </application-config>
    As well as I have included reference to that package within the classpath of the deployed application. Also JAR file that contains that package residing in the physical server directory (in .../server0/additional-lib)
    Actually it works on SAP EP 6. However it does not work for SAP EP11 version.
    What am I missing?
    Any suggestion is greatly appreciated.

    Thank you Prakash.
    I already resolved it.
    So, I had to make sure that:
    1. class path has it
    2. portalapp.xml has the SharingReference
    3. PAR file includes the JAR file in the PORTAL-INF/lib

  • Help!! cannot find files outside class dir

    Directory Structure:
    App
    |-src
    |-classes
    | |-App
    | |-...Packages
    |-resource
    |- images
    I am having problems finding the files in the resource directory from the classes in the classes directory.
    Currently, I am trying:
    InputStream is = ClassLoader.getSystemResourceAsStream("app.properties");
    and running with: java -cp .;../resource App.MainClass
    whats wrong? and Is it different if I use a JAR file?

    I can only get it working if the "resource" directory is in amongst the packages
    App
    |- classes
    | |- App
    | �  |.. packages
    | �  |- resource
    |- src
    and use :
    InputStream is = ClassLoader.getSystemResourceAsStream("App/resource/app.properties");

  • Why cant we put anything outside classes ?

    i couldnt think about any other title,as i am getting more and more confused.
    this is what i know :
    an object is "something" which has got some functionality && exists in memory (thats why real-world).
    why cant we create objects of "only" methods ?
    to be exact,i cant understand why java needs to put everything in the class?
    eg.
    public static void main(String args[])
    int i;
    i=i+5;
    this method should be able to form an object, it has got both data members, and it can call another function to modify the data.
    why do we NECESSARILY need to put this in a class ?

    paul.miner wrote:
    dpux wrote:
    i know its a design specification...but what advantage does it give ??
    josAH gave a valid point, but are there some others ?Old (current?) PHP is an example of what happens when you have a global namespace. Thousands upon thousands of functions with ugly names or stupid prefixes/suffixes ("real", "2", etc.). Static methods in a non-instantiable class are basically like creating namespaces for global methods.
    It's also much easier to find functions that belong together grouped in a class.True, but if "global functions" had been allowed in Java, I bet you a doughnut they would have used package names as a name space, in exactly the same way this is done with classes and interfaces.
    But again, idle speculation like this is a waste of time...

  • Accessing a method from an outside Class

    I am working on a program that will create an array list and hashmap of 3 shapes--squares,triangles and circles. I have created classes for each shape as well as a class that creates arrays of these shapes (called ShapeGenerator).
    Now I need to create a class that will call ShapeGenerator to create the shapes and then put them into an arraylist and hashmap. Right now I just can't get seem to call the methods from ShapeGenerator to create the arrays. What follows is the code I've written. Any guidance would be appreciated. Thanks in advance...
    public class ShapeMaker{
         public ShapeMaker(){
    public ShapeGenerator[] makeShapes(){
         ShapeGenerator[] myShapeGenerator = new ShapeGenerator();
         myShapeGenerator.createSquares(5);
         return createSquares;
    public static void main(String[] args){
         ShapeMaker mySM = new ShapeMaker();
         mySM.makeShapes();
         System.out.println("I made a Shape");
    }

    ShapeGenerator[] myShapeGenerator = new ShapeGenerator();
    new ShapeGenerator will return a single instance of ShapeGenerator - Not an array.
    to create a new ShapeGenerator:
    ShapeGenerator sg=new ShapeGenerator();
    then your method call:
    Object squares[]= sg.createSquares(5);
    or you could just do:
    Object squares[]=new ShapeGenerator().createSquares(5);
    makeShapes() should then return an array of Object (or even better do you have a base Shape class?)
    So we finally end up with something like:
    public class ShapeMaker{
    public ShapeMaker(){
    public Object[] makeShapes(){
    ShapeGenerator myShapeGenerator = new ShapeGenerator();
    return myShapeGenerator.createSquares(5);
    public static void main(String[] args){
    ShapeMaker mySM = new ShapeMaker();
    mySM.makeShapes();
    System.out.println("I made a Shape");
    Excuse any typos but I have not tried to compile this as I don't have a myShapeGenerator etc and I'm too tired (or lazy) to write one.
    Good luck.

Maybe you are looking for

  • Mac Mini or Apple TV as a media server.

    I am planning on setting up a media server and I'm not sure what would be the best choice. I would prefer to use a Mac Mini, but would I loose the video quality that I would get from an Apple TV? The Apple TV specs indicate: Video formats supported *

  • Migration of Tax calculation procedure---TAXINJ to TAXINN

    Hi Gurus, Currently we are doing technical upgrade from 4.7 to Ecc 6.0. Considering benefits and advantages of TAXINN procedure,we want to migrate from TAXINJ to TAXINN so that it will also support CRM. Kindly help me about the roadmap and guide for

  • Message in Oracle 10g

    Hi , We are upgrading to 10g From 6i. in 6i forms to display messages in multiple lines we used CHR(13) . This seems to be not working in 10g instead of splitting the messages in 2 lines , it has joining it with a square box (junk char) can u please

  • GridView Sorting with multiple word in header

    Dear All we have dynamic GridView. we want to sort the gridview. we have multiple words in the header column like (Chicken Burger, Small Pizza , Chicken Roll etc). i m using below code but its giving me error on clicking header (Chicken Burger) like

  • Assign keyboard shortcuts for special characters.

    I am using Microsoft Word 08 and taking a Latin course. I want to be able to make a keyboard shortcut to insert the long symbols over vowel: Ā Ē Ī Ō Ū ā ē ī ō ū. When I go to Insert then Symbol none of these show up on the pallet. As of now I have to