Protected methods in abstract classes

Hello All
I have some problem which I cannot find a workaround for.
I have three classes:
package my.one;
public abstract class First {
  protected void do();
  protected void now();
package my.one;
public class NotWantToHave extends First {
  protected First obj;
  public NotWantToHave(First O) { obj = O; }
  public void do() { obj.do(); }
  public void now() { obj.now(); }
package my.two;
public class Second extends my.one.First {
  protected void do() { System.out.println("Second does"); }
  protected void now() { System.out.println("Second does now"); }
package my.three;
public class Three extends my.one.First {
  protected my.one.First obj;
  public Three(my.one.First O) { obj = O; }
  protected void do() { System.out.println("Doing"); }
  protected void now() { obj.now(); } // Not possible, see later text
Problem is, as one can read in http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html , it says that you cannot access protected members and methods from classes if they are in a different package. However, since my class Three should not concern about the method now() but should use from some other class that implements (i.e. class Second), the question I have is how to do?
One way would be to implement a class that simply make a forward call to any protected method in the same package the abstract class is in like in class NotWantToHave and pass it to the constructor of class Third while this class was created with an instance of class Second. However, such a call would look very clumsy (new my.three.Third(new my.one.NotWantToHave(new my.two.Second()));). Furthermore, everyone could create an instance of class NotWantToHave and can invoke the methods defined as protected in class First, so the access restriction would be quite useless.
Does anyone has a good idea how to do?

Hi
One way I found is to have a nested, protected static final class in my super-class First and provide a protected static final method that returns a class where all methods of the super-class are made public and thus accessible from sub-classes at will. The only requirement is that a sub-class must invoke this method to encapsulate other implementations of the super-class and never publish the wrapper class instance. This will look as follows:
package my.one;
public abstract class First {
  protected final static class Wrap extends First { // extend First to make sure not to forget any abstract method
    protected First F;
    public void do() { F.do(); }
    public void now() { F.now(); }
    protected Wrap(First Obj) { F = Obj; }
  } // end Wrap
  protected final static First.Wrap wrap(First Obj) { return new First.Wrap(Obj); }
  protected abstract void do();
  protected abstract void now();
} // end First*******
package my.two;
public class Second extends my.one.First {
  protected void do() { System.out.println("Second does"); }
  protected void now() { System.out.println("Second does now"); }
} // end Second*******
package my.three;
public class Three extends my.one.First {
  protected my.one.First.Wrap obj;
  public Three(my.one.First O) { obj = my.one.First.wrap(O); }
  protected void do() { System.out.println("Doing"); }
  protected void now() { obj.now(); } // Not possible, see later text
} // end Third*******
In this way, I can access all methods in the abstract super class since the Wrap class makes them public while the methods are not accessible from outside the package to i.e. a GUI that uses the protocol.
However, it still looks clumsy and I would appreciate very much if someone knows a more clear solution.
And, please, do not tell me that I stand on my rope and wonder why I fall down. I hope I know what I am doing and of course, I know the specification (why else I should mention about the link to the specification and refer to it?). But I am quite sure that I am not the first person facing this problem and I hope someone out there could tell me about their solution.
My requirements are to access protected methods on sub-classes of a super-class that are not known yet (because they are developed in the far, far future ...) in other sub-classes of the same super-class without make those methods public to not inveigle their usage where they should not be used.
Thanks

Similar Messages

  • How to Access Protected Method of a Class

    Hi,
         I need to access a Protected method (ADOPT_LAYOUT) of class CL_REIS_VIEW_DEFAULT.
    If i try to call that method by using class Instance it is giving error as no access to protected class. Is there any other way to access it..

    Hi,
        You can create a sub-class of this class CL_REIS_VIEW_DEFAULT, add a new method which is in public section and call the method ADOPT_LAYOUT of the super-class in the new method. Now you can create an instance of the sub-class and call the new sub-class method.
    REPORT  ZCD_TEST.
    class sub_class definition inheriting from CL_REIS_VIEW_DEFAULT.
    public section.
      methods: meth1 changing cs_layout type LVC_S_LAYO.
    endclass.
    class sub_class implementation.
    method meth1.
      call method ADOPT_LAYOUT changing CS_LAYOUT = cs_layout.
    endmethod.
    endclass.
    data: cref type ref to sub_class.
    data: v_layout type LVC_S_LAYO.
    start-of-selection.
    create object cref.
    call method cref->meth1 changing cs_layout = v_layout.

  • Protected method in Final Class

    Hi all
    Can we have protected method in Final class ?
    If so how is it possible ?
    Vicky

    Final classes cannot have subclasses and hence no need of protected methods.
    No comments on possibility.
    Check this link from SAP help to know more :
    http://help.sap.com/saphelp_nw70/helpdata/en/dd/4049c40f4611d3b9380000e8353423/content.htm
    Hope this helps you.
    Edited by: Harsh Bhalla on Dec 19, 2009 3:35 PM

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Final methods in abstract classes?

    Hi, why is it possible to define a final method in an abstract class? The theory behind a final method doesn't say that a final method couldn't be overridden?
    Marco

    So it's formally correct but it doesn't have any
    sense, does it?You sound very confused. A final method in an
    abstract class has just the same semantics and
    makes just as much sense as in a non-abstract
    class.
    The semantics of a final method is simply that
    it cannot be overridden in subclassed. Both
    abstract and non-abstract classes can be
    subclasses. So why do you think there should be any
    difference?Actually i was confused now it's clear. I was too binded to the concept that the extending class SHOULD(not for a formal reason, but for a 'design' one) write the implementation of the methods defined in the abstract class. Now i see that, actually, by defining a final method in an abstract class we are defining our design as implemented and clients(i.e. subclasses) can only use it.
    Thank you,
    Marco

  • ECATT: How to access a protected method of a class with eCATT?

    Hi,
    These is a class with a protected method. now i am willing to automate the scenario with eCATT. Since the method is Protected i am unable to use createobj and use callmethod. Could anyone suggest me a work around for this ?
    Regards
    Amit
    Edited by: Amit Kumar on Jan 10, 2012 9:53 AM

    Hello Anil,
    You can write ABAP Code to do that inside eCATT Command.
    ABAP.
    ENDABAP.
    Limitation of doing that is you can only use local variable inside ABAP.... ENDABAP. bracket.
    Regards,
    Bhavesh

  • How to use protected method of a class in application

    Hi,
      will u please tell me how to use protected method of class in application. (class:cl_gui_textcontrol, method:limit_text)
    Thanks in advance,
    Praba.

    Hi Prabha,
    You can set the maximum number of characters in a textedit control in the CREATE OBJECT statement itself.
    Just see the first parameter in the method . I mean MAX_NUMBER_CHARS. Just set that value to the required number.
    Eg:
    data: edit type ref to CL_GUI_TEXTEDIT.
    create object edit
      exporting
        MAX_NUMBER_CHARS       = 10
       STYLE                  = 0
       WORDWRAP_MODE          = WORDWRAP_AT_WINDOWBORDER
       WORDWRAP_POSITION      = -1
       WORDWRAP_TO_LINEBREAK_MODE = FALSE
       FILEDROP_MODE          = DROPFILE_EVENT_OFF
        parent                 = OBJ_CUSTOM_CONTAINER
       LIFETIME               =
       NAME                   =
      EXCEPTIONS
        ERROR_CNTL_CREATE      = 1
        ERROR_CNTL_INIT        = 2
        ERROR_CNTL_LINK        = 3
        ERROR_DP_CREATE        = 4
        GUI_TYPE_NOT_SUPPORTED = 5
        others                 = 6
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
               WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    In this case, the max: number of characters will be set to 10.
    I hope your query is solved.
    Regards,
    SP.

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

  • Implement method inside abstract class?

    hello everyone:
    I have a question regarding implementation of method inside a abstract class. The abstract class has a static method to swamp two numbers.
    The problem ask if there is any output from the program; if no output explain why?
    This is a quiz question I took from a java class. I tried the best to recollect the code sample from my memory.
    if the code segment doesn't make sense, could you list several cases that meet the purpose of the question. I appreciate your help!
    code sample
    public abstract class SwampNumber
       int a = 4;
       int b = 2;
       System.out.println(a);
       System.out.println(b);
       swamp(a, b);
       public static void swamp(int a, int b)
         int temp = a;
             a = b;
             b = a;
         System.out.println(a);
         System.out.println(b);

    It won't compile.
    You can't instantiate an abstract class before you know anything.
    //somewhere in main
    SwampNumber myNum = new SwampNumber();
    //Syntax ErrorQuote DrClap
    This error commonly occurs when you have code that >>is not inside a method.
    The only statements that can appear outside methods >>in a Java class are >>declarations.Message was edited by:
    lethalwire

  • Using common methods with abstract classes

    hello everyone, i wanted to know if it is bad practice (i imagine it is) to place methods which will be used by multiple classes (computational methods) in an abstract class and mark them as static. When i do this they are always project wide utility classes which dont need an instantiation. When using any of these methods which are common to a project i can then just use..
    Type result = ClassName.DoStaticMethod(...);Thanks for any input,
    Dori
    Edited by: Sir_Dori on Dec 8, 2008 2:01 AM

    Depends on what the methods are meant to do, but I wouldn't make the class abstract. I would instead declare it to be final and have a private constructor.
    Kaj
    Ps. Take a look at the java.lang.Match class.

  • Dynamically invoke methods of abstract class?

    Hi,
    I am using reflection to write a class (ClassA) to dynamically invoke methods of classes. I have an abstract class (ClassB) that has some of the methods already implemented, and some of the methods that are declared abstract. Is there any way that I can:
    (a) invoke the methods that are already implemented in ClassB;
    (b) I have another class (ClassC) that extends ClassB, some of the methods are declared in both classes. Can I dynamically invoke these methods from ClassB?
    Thanks in advance,
    Matt.

    Ok, the program is quite long, as it does other things as well, so I'll just put in the relevant bits.
    What I have is a JTree that displays classes selected by the user from a JFileChooser, and their methods.
    // I declare a variable called executeMethod
    private static Method executeMethod;
    // objectClass is a class that has been chosen by the user.  I create a new instance of this class to execute the methods.
    Object createdObject = objectClass.newInstance();
    // methodName is the method selected by the user.  objectClassMethods is an array containing all the methods in the chosen class.
    executeMethod = objectClassMethods[j].getDeclaringClass().getMethod(methodName, null);
    Object executeObject = executeMethod.invoke(createdObject, new Object[]{});Ok, here are the test classes:
    public abstract class ClassB{
         private int age;
         private String name;
         public ClassB(){ age = 1; name="Me";}
         public int getAge(){ return age; }
         public String getName(){ return name; }
         public void PrintAge(){System.out.println(age);}
         public void PrintName(){System.out.println(name);}
         public abstract void PrintGreeting();
    public class ClassC extends ClassB{
         public ClassC(){super();}
         public void PrintAge(){
              System.out.println("I am " + getAge() + " years old.");
         public void PrintGreeting(){
           System.out.println("Hello");
    }Now, I can print out the PrintAge method from ClassC (i.e. have it output "Hello" to the command line, how can I, say, get it to output the result of PrintName from ClassB, this method does not appear in ClassC. As you can see at the top, I can create a new instance of a normal method (in this case, ClassC), and have it output to the command line, but I know that I can't create a new instance of an abstract class. And since PrintName is implemented in abstract class ClassB, how do I get it to output to the command line?
    Thanks,
    Matt.

  • Non-abstract methods in a Abstract class

    Abstract Class can contain Non-abstract methods.
    and Abstract Classes are not instantiable as well
    So,
    What is the purpose of Non-abstract methods in a Abstract class.
    since we can't create objects and use it
    so these non-abstract methods are only available to subclasses.
    (if the subclass is not marked as abstract)
    is that the advantage that has.(availability in subclass)
    ??

    For example, the AbstractCollection class (in
    java.util) provides an implementation for many of the
    methods defined in the Collection interface.
    Subclasses only have to implement a few more methods
    to fulfill the Collection contract. Subclasses may
    also choose to override the AbstractCollection
    functionality if - for example - they know how to
    provide an optimized implementation based on
    characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
    Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about."

  • Access overriden method of an abstract class

    class Abstract
    abstract void abstractMethod(); //Abstract Method
    void get()
    System.out.print("Hello");
    class Subclass extends Abstract
    void abstractMethod()
    System.out.print("Abstract Method implementation");
    void get()
    System.out.print("Hiiii");
    In the above code, i have an abstract class called "Abstract", which has an abstract method named "abstractMethod()" and another method called "get()".
    Now, this class is extended by "Subclass", it provides implementation for "abstractMethod()", and also overrides the "get()" method.
    Now my problem is that i want to access the "get()" method of "Abstract" class. Since it is an abstract class, i cant create an object of it directly, and if i create an object like this:
    Abstract obj = new Subclass();
    then, obj.get() will call the get() method of Subclass, but how do i call the get() method of Abstract class.
    Thanks in advance

    hey thanks a lot,, i have another doubt regarding Abstract classes.
    i was just trying something, in the process, i noticed that i created an abstract class which does not have any abstract method, it gave no compilation errors. was wondering how come this is possible, and what purpose does it solve?

  • Abstract class method polymorphically using constructors?

    how can i have a method defined in an abstract superclass call a constructor of the actual class running the method?
    abstract class A {
    public List getMultple() {
    List l = new ArrayList();
    for (short i=0;i<4;i++) {
    l.add(this());//<obviously this breaks
    return l
    or something like that. A won't run this method, but its children will...and they can call their constructors, but what do i put here to do that?
    i've tried a call back. an abstract method getOne() in the superclass forces each child to define that method and in each of those i return the results of a constructor. that works fine.
    the problem is i want to abstract this method out of each of these children classes cause its the exact same in each one, just using a different constructor to get multiple of each in a list. so if i use this callback method, then i am not saving the number of methods in each class, so why bother at all?
    any ideas?

    I still say you are coming at it from the wrong angle. A super class is not the way to go. What you are doing sounds like something very similar to something I did not too long ago.
    My requirement was that I had tab delimited text files filed with data that I had to parse. Each line would be used to instantiate one object, so a particular file could be used to instantiate, for example, a thousand objects of the same class. There were different types of files corresponding to different classes to instantiate instances of.
    Here is the design I ended up using.
    An object of class DataTextFileReader is instantiated to parse the text file and generate objects. It includes code for going line by line, handling bad lines and generating objects and reports. The constructor:
    public DataTextFileReader(File inputFile, LineParser<T> theLineParser)LineParser is an interface with one method:
    public T read(String line);When you call a load() method of the DataTextFileReader, it does its thing with the aid of the LineParser's read method, to which each line is passed, and stores the generated objects in an ArrayList. This can be returned by using another method. There are other methods for getting the reports, etc.
    Obviously, the LineParser chosen needs to have code appropriate for parsing the lines in question, so you have to choose and instantiate the right one.
    I find this design to work well. I arrived at it after spending hours giving myself headaches trying to come up with a design where there was a superclass roughly equivalent to the DataTextFileReader mentioned above, and classes extending this that fulfilled the duty of the LineParsers mentioned above... rather like what you are trying to do now.
    I did not care for the solution at first because it did not give me the "Ah, I am clever!" sensation I was expecting when I finally cracked the problem using inheritance, but I quickly came to think that it was much better OOD anyway.
    The LineParsers mentioned above are essentially embodiments of the Factory pattern, and I would recommend you do something similar in your case. Obviously your "constructors" all have to be different, so you should make a separate class for each of those. Then you can put the code that performs the query and loops to create loads of objects in another class called something like DatabaseDepopulator, using appropriate generics as in my example. Really it is the same problem, now that I look at it.
    This will also result in better separation of concepts, if you ask me. Why should the class constructor know how to parse a database result query, much less perform the query? It has nothing to do with databases (I presume). That is the job of an interpreter object.
    As a final note, remember... 95% of the time you feel like the language won't let you do what you want, it is because you shouldn't anyway.
    Drake

  • How to get protected method ?

    I thought i can get protected method of my class when calling a Class.getMethod(String, Class []) in another class which inside the same package. However, it seem that i can't do that because it throw me a NoSuchMethodException when the method was protected. I thought all classes in same package can access the protected methods or fields of each other ??? Why ?
    So, how i'm able to get the protected method in runtime ? (Hopefully no need to do anything with the SecurityManager)

    It is working
    Pls try the following program ...
    public class p1 {
    public static void main(String as[]) {
    p2 ps2 = new p2();
    ps2.abc();
    class p2 {
    protected void abc() {
    System.out.println("Hello");
    regards,
    namanc

Maybe you are looking for