Question on Assigning Sub Class References

Hi Friends,
I have small doubt regarding Assigning Class Reference to Super Class or Interface.
List list= new ArrayList(); or Collection collection = new ArrayList();
Map map=new HashMap();
if i assing like above i may loose some of the specilized methods of ArrayList,Map etc...
but most of the people are creating the objects in above fashion.
can any body list out the advantages.
Thanks in Advance!

Agreed, you do lose some of the specialised methods.
But sometimes its functionality you don't need.
If your function takes a "Collection" it doesn't matter if its ArrayList or Set - you're just interested in the Collection Interface (common use case would be to obtain an Iterator to the underlying datastructure)
Writing to the interface means that you can change the implementation at will.
You can swap an ArrayList for a LinkedList. A HashMap for an LinkedHashMap or TreeMap. And the rest of your code is untouched, because it presumed nothing about the implementation.

Similar Messages

  • Less dumb follow-up question about super/sub classes in WDJ?

    This is a follow-up question to the question which Maksim answered in this thread:
    Dumb question about super/sub classes in WDJ
    Question:
    Is there any kind of weird C++-like statement that you can put at the top of a WDJ module to force the module to interpret any reference to superclass A as a reference to some specific subclass B of A ???

    David,
    1. Java has no preprocessor, so C++ tricks are not available. Also I would not recommend such tricks even in C++ if you don't want to turn your colleagues working with same code into personal enemies.
    2. The phrase "easier to create a WDJ custom class loader " makes me smile. First, it's not that simple to interfere WDJ class loading scheme. Plus custom class loaders is not trivial Java topic per se.
    3. The problem "replace all A-s with B-s" is typically solved using one or another GoF creation patterns, like <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract Factory</a> or <a href="http://en.wikipedia.org/wiki/Factory_method_pattern">Factory Method</a>. You may use them with custom class loader, if you really want to
    By the way, all UI controls in WD are created using Abstract Factory (role played by view). So you may use this as good example.
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • Trouble assigning sub class to super class array

    Hi,
    I would greatly appreciate some help with the following:
    I want to assign a sub class to a super class array but the following code does not work
    where the board is comprised of the super class
         private static void makeMove( int X, int Y, int moveX, int moveY )
              ChessPiece tempChessPiece = ( ChessPiece ) board[ X ] [ Y ];
              board[ X ] [ Y ].setType( UNDEFINED );
              board[ moveX ] [  moveY  ] = tempChessPiece;
         }

    I have got this code to work but it does not appear
    to be very efficient to me as i dont recycle the
    objects.
    Any thoughts?The objects will be recycled by the garbage collector. It's very efficient so there's very little performance penalty in creating objects and releasing objects.
    Still, another alternative is to represent an empty square with null. In that case the code becomes,
    private static void makeMove( int selectedX, int selectedY, int moveToX, int moveToY ) {
       board[moveToY][moveToX] = board[selectedX][selectedY]; // piece to new position
       board[selectedX][selectedY] = null; // remove from old
    }I don't know your exact design but that should work. It's kind of natural too. If a square is empty there's no piece object there at all. No new object has to be created and that explicit cast is gone.

  • Why a sub class reference cannot hold a super class object

    class a
    class b extends a
    public static void main(String args[])
    b o1=new a();
    I know this code wont compile but i need explanation on why subclass reference cannot hold superclass object

    In short, because the subclass reference might be expected to point to an object with methods or members that the superclass object does not have.

  • Dumb question about super/sub classes in WDJ

    In WDJ, if you want to use some method M of some subclass B that inherits from some class A (because you've customized method M in superclass B), don't you call the method of class B in your WDJ code ???

    David,
    Actually, this is just Java.
    As with any OOP language you get polymorphic objects behavior -- you may use subclass whenever superclass is necessary. Also the version of method called will be always method from the "most derived class" -- actual class used when instantiating object, not the version from class used for declaring variable.
    By the way, this differs java from C++/C# -- all methods are virtual by nature, you should not use "override" keyword to explicitly mark method as overwritten. This C# feature bugs me several times when I did my first steps with .NET.
    Valery Silaev
    SaM Solutions
    http://www.sam-solutions.net

  • How to use application class reference in the controller methods of BSP

    Hi,
    I have created a bsp application and also created an application class and assigned it to the application class. In the application class, I have created attribute TEXT type string(public and instance parameter).
    In the controller let's say main.do, I am trying to give a value to to the text by adding the following code.
    application->text = 'test'.
    I am getting syntax error saying field 'text' is unknown. It is not contained in one of the specified tables nor defined by DATA statement. 
    Please can someone let me know how to use the application class in the coding with an example. I couldn't find how exactly this has to be reference. Please help.
    Best regards
    Siva

    Hi,
    if you are having main controller and sub-controller then you may need to use below coding to use application class reference.
    *Data declaration
      DATA:  obj_cntrl        TYPE REF TO cl_bsp_controller2,
             obj_sub_cntrl   TYPE REF TO z_cl_sub_cntl,
             application TYPE REF TO z_cl_application.
    *Get the controller
      CALL METHOD obj_main_cntrl->get_controller   "obj_main_cntrl is the object of main controller
        EXPORTING
          controller_id       = 'SUB'   "Controller ID
        RECEIVING
          controller_instance = obj_cntrl  .
      obj_sub_cntrl ?= obj_cntrl  .
      application ?= obj_sub_cntrl ->application.
    or simply use below code in your controller method.
      application ?= me->application.
    Thnaks,
    Chandra

  • Instantiation of similar object over a super class deciding the sub class

    Hello all
    First, sorry if I'm duplicating an already answered question. I didn't searched very deep.
    Initial position:
    I have 2 Object (A1 and A2) which share the most (about 90%) of their instance variables an the associated methods. The values of the instance variables are retrieved in the real implementation from a stream. Depending of the data of the stream, I have to instantiate either a A1 or A2 object.
    A test implementation (using an int in case of the stream):
    The super class A:
    package aaa;
    public class A
      protected int version = -1;
      protected String name = null;
      protected AE ae = null;
      protected A()
      protected A(int v)
        // Pseudo code
        if (v > 7)
          return;
        if (v % 2 == 1)
          this.version = 1;
        else
          this.version = 2;
      public final int getVersion()
        return this.version;
      public final String getName()
        return this.name;
      public final AE getAE()
        return this.ae;
    }The first sub class A1:
    package aaa;
    public final class A1 extends A
      protected A1(int v)
        this.version = v;
        this.name = "A" + v;
        this.ae = new AE(v);
    }The second subclass A2:
    package aaa;
    import java.util.Date;
    public final class A2 extends A
      private long time = -1;
      protected A2(int v)
        this.version = v;
        this.name = "A" + v;
        this.time = new Date().getTime();
        this.ae = new AE(v);
      public final long getTime()
        return this.time;
    }Another class AE:
    package aaa;
    public class AE
      protected int type = -1;
      protected AE(int v)
        // Pseudo code
        if (v % 2 == 1)
          this.type = 0;
        else
          this.type = 3;
      public final int getType()
        return this.type;
    }To get a specific object, I use this class:
    package aaa;
    public final class AFactory
      public AFactory()
      public final Object createA(int p)
        A a = new A(p);
        int v = a.getVersion();
        switch (v)
        case 1:
          return new A1(v);
        case 2:
          return new A2(v);
        default:
          return null;
    }And at least, a class using this objects:
    import aaa.*;
    public final class R
      public static void main(String[] args)
        AFactory f = new AFactory();
        Object o = null;
        for (int i = 0; i < 10; i++)
          System.out.println("===== Current Number is " + i + " =====");
          o = f.createA(i);
          if (o instanceof aaa.A)
            A a = (A) o;
            System.out.println("Class   : " + a.getClass().getName());
            System.out.println("Version : " + a.getVersion());
            System.out.println("Name    : " + a.getName());
            System.out.println("AE-Type : " + a.getAE().getType());
          if (o instanceof aaa.A2)
            A2 a = (A2) o;
            System.out.println("Time    : " + a.getTime());
          System.out.println();
    Questions:
    What would be a better way to encapsulate the logic into their respective objects ? Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?
    Thanks in advance
    Andreas

    Hello jduprez
    First, I would thank you very much for taking the time reviewing my problem.
    Just for the record: have you considered regular serialization? If you control the software at both ends of the stream, you could rely on standard serialization mechanism to marshall the objects and unmarshall them automatically.In my case, I can't control the other site of the stream. At the end, the data comes from a FileInputStream and there aren't objects on the other site, only pur binary data.
    - It seems you have one such factory class. Then you already have encapsulated the "determine class" logic, you don't need to add such logic in superclass A.I thought from an OO view, that the super class A is responsible of doing that, but that's where the problem starts. So at the end, it's better doing it in the factory class.
    - A itself encapsulates the logic to load its own values from the stream.
    - A1 and A2 can encapsulate the logic to load their own specific value from a stream (after the superclass' code has loaded the superclass' attributes values).
    My advise would be along the lines of:
    public class A {
    .... // member variables
    public void load(InputStream is) {
    ... // assign values to A's member variables
    // from what is read from the stream.
    public class A1 extends A {
    ... // A1-specific member variables
    public void load(InputStream is) {
    super.load(is);
    // now read A1-specific values
    public class AFactory {
    public A createA(InputStream is) {
    A instance;
    switch (is.readFirstByte()) {
    case A1_ID:
    a = new A1();
    break;
    case A2_ID:
    a = new A2();
    break;
    a.load(is);
    }The example above assumes you have control over the layout of the data in the stream (here for a given A instance, the attributes defined in A are read first, then come the subclass-specific attributes.
    The outcome is: you don't have to create a new A( ) to later create another instance, of a subclass.I like the idea. In the AFactory, is the "A instance;" read as "A a;" ?
    Is there a way to let the super class A itself identify the type of the object and then extend from A to either A1 or A2 ?Note I initially read this question as "can an instance of a class mutate into another class", to which the answer is no (an object has one single, immutable class; it is an instance of this class, and of any superclass and superinterface, but won't change its class at runtime).Yes, I have been thinking about a way for mutating into a subclass to keep the already initialized values from the A class without copying or parsing again. But preventing an instance of an A class will be my way. So, in this aspect, Java didn't changed in the last 10 years... It's a long time ago I've used Java for some real projects.
    You can, however, create an instance of another class, that copies the values off a priori A instance. Your example code was one way, another way could be to have a "copy constructor":
    public class A {
    public A(A model) {
    this.att1 = model.att1;
    this.att2 = model.att2;
    public class A1 {
    public A1(A model) {
    super(model);
    ... // do whatever A1-specific business
    )Still, I prefer my former solution less disturbing: I find the temporary A instance redundant and awkward.Nice to know. I prefer the first solution too.
    Thank you again for the help and advices. My mind is searching sometimes for strange solutions, where the real is so close ;-)
    Andreas

  • How can i use class reference from an array effeciently?

    Hi,
    I made some test here with getting a class reference from an array and using the reference's methods or variables.
    Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
    Example #1----Strongly typed
    Var reference:Person;
    Var num:int;
    //Assignation
    reference=arrayEx[0];-----IT IS SLOW HERE
    //Use
    num=reference.number --- IT IS FAST HERE
    Example #2---Not typed
    Var reference:*;
    Var num:int;
    //Assignation
    reference=arrayEx[0]; ---- IT IS FAST HERE
    //Use
    num=reference.number ---IT IS SLOW HERE
    No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
    If someone knows how, please tell me,
    Dominik

    Hi,
    I made some test here with getting a class reference from an array and using the reference's methods or variables.
    Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
    Example #1----Strongly typed
    Var reference:Person;
    Var num:int;
    //Assignation
    reference=arrayEx[0];-----IT IS SLOW HERE
    //Use
    num=reference.number --- IT IS FAST HERE
    Example #2---Not typed
    Var reference:*;
    Var num:int;
    //Assignation
    reference=arrayEx[0]; ---- IT IS FAST HERE
    //Use
    num=reference.number ---IT IS SLOW HERE
    No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
    If someone knows how, please tell me,
    Dominik

  • Assign Valuation Class to Company Code

    Hi Gurus...
    Quick Question: we are migrating from R3 to ECC 6. One of Treasury Management config points is Valuation Class definition. R3 used to have a config point in IMG called Assign Valuation Class to Company Code/Transaction Type. But I cannot find same in ECC6. Even CTRL-F does not help. Did it get moved and renamed?
    Thanks,
    JS

    Hi,
    Don't know the IMG path but what you can try:
    1. Go to the required IMG transaction in R/3 and look up the table / view (click on a field in the IMG transaction / push F1 / click icon Technical Information)
    2. In ECC 6 go to transaction SM30, fill in the table / view name from step 1
    3. Click icon Customizing
    4. In pop-up click Continue w/o Specifying Project
    5. An overview appears with IMG config points where the specified table / view is maintained. Choose the appropiate one by double clicking.
    Prerequisite is the existence of an IMG activity exists for object maintenance.
    Regards,
    Andre

  • FI-AA: Assignment asset class to chart of depreciation

    Hi all,
    does anybody know whether it's possible to assign asset classes to a specific chart of depreciation (or let's say to delete this assignment)?
    The background of the question is the following: Some asset classes should not be used in some company codes. All these company codes use the same chart of depreciation, so I thought there must be a possibility to delete the assignment of this asset class to this chart of depreciation. Unfortunately, I haven't found this setting in the IMG.
    The SAP Message no. AC 012 tells for example, that there is an assignment "asset class to chart of depreciation". This is the message:
    In order to be able to assign chart-of-depreciation-dependent data to asset class 120204, the following conditions have to be met. You have to have already
    1. Defined at least two active charts of depreciation
    2. Assigned asset class 120204 to more than one chart of depreciation
    However, at the moment this asset class is only assigned to chart of depreciation 1.
    As we have definitely more than one active chart of depreciation, there must be this assignment, but how can I change it?
    I've seen that I can set a block for an asset class in a chart of depreciation in transaction OAYZ (ANKB-XSPEB / Indicator: Block asset class chart of depreciation-specifc). But I think that I will still see the asset class in the match code search (F4) when I set this indicator.
    Does anybody know how I can delete an asset class form a chart of depreciation so that it won't be found via match code search? I've checked almost the whole FI-AA tree but haven't found a solution...
    Thank you very much!
    Regards,
    Peter

    Hi Eric,
    thanks for your answer. As far as I can see, the option "chart of depreciation only" in transaction AM05 has the same effect than the parameter "chart of depreciation" in transaction OAYZ.
    As I receive a transport request via transaction AM05, it seems that this changes the same customizing table.
    Fortunately, all company codes in this chart of depreciation need the same settings, so a validation rule seems not to be necessary.
    It's just strange that there is no possibility to edit the assignment asset class to chart of depreciation in customizing (I think the assignment to all asset classes in the system will be created automatically when I copy the chart of depreciation). I think the only possibility would be to edit the respective tables manually (what I definitely won't do).
    Another strange thing I see in the system: There are 2 asset classes 120203 and 120204, which are both set up equally. When I try to block these in AM05, I'll receive the error message AA 111 for asset class 120204, while the asset class 120203 can be blocked without problems. When I use matchcode search F4, I can see 120203 while 120204 is not found.
    Message AA111 is the following:
    Chart of dep. 100 does not exist in class 120204 (Create chart of deprec.)
    Diagnosis
    Chart of depreciation 100 does not exist in class 120204.
    Procedure
    Create the chart of depreciation 100 for asset class 120204 using the transaction 'Create asset class' and the function 'Create chart of dep.'.
    There is the assignment asset class to chart of depreciation.
    When I check asset class 120204 in OAYZ (Determine Depreciation Areas in the Asset Class) I'll get the following message (I don't get this message when I check 120203):
    Deprec. area 50 was changed and deactivated. Please check.
    Message no. AC 631
    Diagnosis
    Depreciation area 50 was added to asset class 120204 because this depreciation area was newly created in Customizing.
    System Response
    The system adds the new depreciation area to the asset class, but its status is 'deactivated.'
    Procedure
    Check if this action by the system is correct. Maintain the depreciation areas in the asset class, and remove the 'deactivated' indicator there, if you choose.
    For sure, depreciation area 50 was not newly created in customizing (as stated in the error message), as this depreciation are is in production for years! There must be another reason for this.
    However, this says to me that the assignment asset class to chart of depreciation is created by SAP automatically and this can't be influenced.
    Therefore I'll just block the asset class in the chart of depreciation with the disadvantage, that I'll see this asset class when I use the matchcode search F4 (e.g. in AS01). This seems to be the only solution.
    Thanks again for your help (you got some points for that ;-).
    Regards,
    Peter

  • Assigning of Classes to superior classes Using SXDA_Tools...Urgent

    Hi All,
    I have a requirement in which i have to create classes(Material classes, CL01) and subclasses for them. In the second step i will have to assign the created sub classes to their respective superior classes.
    I could create classes using batch input program "RCCLBI01" and object type BUS1003 from transaction SDXA_TOOLS.
    However i am not sure how to assign the created classes to their respective superior class. Does anyone know any direct input program or batch input programs to assign a class to its superior class ??

    See [http://forums.sun.com/thread.jspa?threadID=5333060&tstart=0]. In general, if you use third-party libraries in your code, you should include these libraries in Javadoc's classpath option when generating documentation.

  • Java Sub-Classing Error.  Please Help!

    I am trying to understanding some classing sub-classing and the convertion exercise. The errors appear with the code at the bottom at compilation.
    HelloWorld.java:7: cannot resolve symbol
    symbol : method uniqueInSubSayHello()
    location: class SayHello
    sh2.uniqueInSubSayHello();
    ^
    HelloWorld.java:11: cannot resolve symbol
    symbol : method uniqueInSubSayHello()
    location: class SayHello
    sh2.uniqueInSubSayHello();
    ^
    class HelloWorld {
         public static void main (String args[]) {
              subSayHello subsh=new subSayHello();
              SayHello sh2=subsh;
              sh2.haha();
              sh2.uniqueInSubSayHello();
         int callUnique() {
              sh2.uniqueInSubSayHello();
    class SayHello {
         public SayHello() {
         public void haha() {
    class subSayHello extends SayHello {
         public subSayHello() {
         void uniqueInSubSayHello() {

    On line 7, sh2 points to an object of type SayHello (as you assigned two lines earlier) and therefore does not know about method UniqueUnSubSayHello.
    On line 11, sh2 has not been declared, since sh2 is not a variable declared globally within class SayHello. Therefore, it is not found.
    Best regards,
    Cemil

  • Class reference internal table

    Hello Gurus,
    i have an internal table filled with class references and i need to acces the one field of a structure of every class.
    I am now trying something like this:
    loop ref_table assigning <l_wrk_ref_but0id>.
          IF <l_wrk_ref_but0id>->m_str_but0id-type = /gkv/cd40_cl_const=>con_pkkv.
          ENDIF.
    endloop.
    I need the field "type" in the structure "m_str_but0id" of every class (reference) in the table. The error that i'm getting is: "Field m_str_but0id unknown".
    Please help.
    Ioan Constantin.

    Hello Ioan
    You have to access the field dynamically as well:
    DATA:
       ld_structure  TYPE <name of structure>,
       ld_attribute    TYPE tabname,
       ld_field          TYPE fieldname.
    FIELD-SYMBOLS:
      <ls_struct>     TYPE any,
      <ld_fld>           TYPE any.
    ld_attribute = 'M_STR_BUT0ID'.
    ld_field       = 'TYPE'. 
    loop ref_table assigning <l_wrk_ref_but0id>.
         ASSIGN <l_wrk_ref>but0id>->(ld_attribute) TO <ls_struct>.
         ASSIGN COMPONENT (ld_field) OF STRUCTURE <ls_struct> TO <ld_fld>.
    "      IF <l_wrk_ref_but0id>->m_str_but0id-type = /gkv/cd40_cl_const=>con_pkkv.
           IF ( <ld_fld> = /gkv/cd40_cl_const=>con_pkkv ).
          ENDIF.
    endloop.
    Even simpler might be the following approach:
    LOOP AT ref_table assigning <l_wrk_ref_but0id>
                    WHERE ( table_line->m_str_but0id-type = /gkv/cd40_cl_const=>con_pkkv ).
    ENDLOOP.
    " Assumption: Itab has class reference type as line type.
    Regards
      Uwe

  • Instantiation of a sub class

    I have a basic question abt instantiating a class.
    I have a base class 'beverage' and a child class 'tea' with a overridden method in child class 'price'.
    I want to know the difference b/w the following instantiating statements:
    - beverage b = new tea();
    - tea t = new tea();
    What exactly happens when compiler sees the first statement?? Is the object 'b' is of type 'tea'???
    Please advice or send me any links which would help in understanding that concept.

    What exactly happens when compiler sees the first
    statement?? Is the object 'b' is of type 'tea'???No. The reference named b is of type Beverage. The object it points to is of type Tea. References are not objects, just pointers to them.

  • Class Reference?

    I can't figure out how to create a reference to a class so I don't have to keep typing the class.staticvar.item
    So usually I have this:
    DocClass.build_class.firstFunction();
    I would rather in my sub class just be able to say;
    private var build_class:Class = Class(getDefinitionByName("DocClass.build_class"));
    so throughout the sub class I only have to type the reference, build_class...
    What am I doing wrong?

    Still can't get it. In a sub class if I try to reference the parent class by doing this
    private var build_stage_class:BuildStageClass = BuildStageClass;   // errror
    private var build_stage_class:BuildStageClass = DocClass.build_stage_class;   // errror
    private var build_stage_class:Class= DocClass.build_stage_class;   // errror
    private var build_stage_class:Class=BuildStageClass;   // errror
    The DocClass starts the BuildStageClass and has a static var called build_stage_class;
    DocClass loads BuildStageClass
    BuildStageClass loads NavClass
    Nav Class trying to reference the BuildStageClass so I can reference the parent class. Obviously this doesn't save any typing however there are sub classes of the sub class which will save typing with a reference.

Maybe you are looking for

  • Is there a way to promote results with exact match?

    Hi, Is there a way to promote (like add results block or something) results with exact match over results that match? (when stemming is on, so the search consider also words with morpholgy match, and sometimes display them at the top, and wWe want to

  • GL Problem  Urgent

    Dear ALl, While creating PO one GL account is picked up automatically,Where that GL is used to maintained and where in Material Management is assign with. Regards, Rita

  • How can a file be accessed by more than one app?

    Hi, I am new to iOS4 and the whole iPhone, iPod technology. I am really a windows user. How can a file be accessed by more than one app. In my case I want to transfer a midi file from my PC to my iPod Touch and be able to open it from a couple of Mid

  • More RAM or better processor?

    Hi All, I'm gonna buy a new iMac for Christmas and I only have budget to upgrade either my RAM memory or my microprocessor. My base configuration would be 8 gb RAM and the core i5 2.9. Which one would you advise me to upgrade? I mainly due photo and

  • Validating the model node

    Hi Experts, I have a requirement of validating( changing field names and changing values based on the conditions) the model node and copy the required values into value node. Bacially , copying the model node elements to value node based on condition