Final&private methods in inheritance

Hi all,
We know that in inheritance private methods are not inherited by sub classes. In addition to this it's also known that final methods are inherited but cannot be changed. Then what is the use of using private methods when there is final methods which cannot be changed, that is why to hide our methods, are they(private methods) something that must be encapsulated as they behave like supporting methods?

Yes, you hide methods by making them private in order to hide implementation details.

Similar Messages

  • Are private methods inherently final?

    You can�t override a private method, so is it inherently final? Will the compiler treat it like a final? I�ve heard that final methods may be inlined by the compiler but haven�t really been able to produce a test to show the advantage of inlining. I know in theory it trades speed for program size, but, if it does work, is it really that much faster? I�m guessing CPU local cache probably eliminates or at least reduces to negligible time the overhead of swapping out the instruction stack to perform a �jump.�
    Thanks for your thoughts. Mostly trying to figure out when to use final methods.

    You can�t override a private method, so is it
    inherently final? Given that that is exactly what the JLS says it would
    suggest that the answer is yes.
    http://java.sun.com/docs/books/jls/second_edition/html
    /classes.doc.html#38958
    I believe the invocation (byte code) is different as
    well (but I didn't look it up) so the VM could
    certainly easily do something with it.Actually, I don't think this is 100% accurate.
    You can replace a private method in a subclass with the same signature (name, arg list) with the same return type. In fact, this is true even if the private method is declared final. It is only when the final method is public (maybe protected and package, I'm not sure) that the compiler complains when you try to extend it.
    � {�                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Private - encapsulation or inheritance (but not both)

    Suppose that your class has some internal computation or logic that it performs, and that you wish to encapsulate this in a method that can not be called by other classes.
    You provide public methods that filter, format, or somehow modify the input and/or output of this encapsulated method.
    class pseudoCodeClass {
    private coreLogic(Objects inputs) {
    Maybe some complicated math stuff;
    Or password stuff;
    Or pay out functionality for a slot machine;
    return(stuff);
    public getUserData(inputs) {
    format/check the inputs;
    coreLogic(inputs);
    format the output;
    Now, how do you leveradge the power of OO inheritance to extend the internal logic that you encapsulated? If you make the interal logic private, then it's encapsulated, but you lose the power of OO inheritance, or you can make it protected and lose the encapsulation. I thought an OO language was supposed to have encapsulation and inheritance, not encapsulation or inheritance. (And, yes I realize that there is some techincal sense in which private methods are still inherited, but I'm talking about the general OO concept of inheritence where it includes overriding or extending.)
    Suppose you want to:
    class pseudoCodeSubclass extends pseudoCodeClass {
    private coreLogic(inputs) {
    super.coreLogic(inputs);
    additional more specific code; // The whole point of OO inheritence
    You can't extend super.coreLogic through your access to super.getUserData because it does all sorts of filtering and formating that is not a part of the internal logic that you wish to extend/override. And, providing other more public accessor methods to the core logic just defeats the encapsulation.
    I have seen many discussions of this, but none with any answers to my satisfaction. One line of answers is that you don't want encapsulated stuff to be part of your object's contract. Some times people with this sort of answer even suggest coppying the code from the super class into the subclass. People with this sort of answer don't seem to even want the option to use inheritence because of the obligation that might go with it. But without the option of inheriting encapsulated logic, they are forced to either use cut and paste (in an OO language that seems wrong to me) or to abandon encapsulation all together. Being forced into those 2 extreems doesn't seem to me like it would simplify future support of your class, and future support seems to be the primary point of the contract line of response.
    The way some people argue about this, I amost want to say - Look! In C you can encapsulate everything you want, and never have to worry about inheritance. (But you still shouldn't have to cut and paste.)
    Another line of response that I have seen is that private methods should only be used in breaking up code that would have gone into a single method. In other words, the private methods aren't really 'units of program logic' they are just a mater of organizational convenience. So if you had:
    public oneBigMessyMethod() {
    100 lines of A;
    100 lines of B;
    100 lines of C;
    you could maintain it as:
    public oneBigMessyMethod() {
    a();
    b();
    c();
    private a() {
    100 lines of A;
    private b() {
    100 lines of B;
    private c() {
    100 lines of C;
    I agree private works well in this situation. Presumably since a(), b() and c() are divided up for convenience rather than because of distinct logical function, you wouldn't want to extend just a() with inheritance. But this also seems to dodge the question. Just because sometimes you might not want encapsulated functionality to be available for extention, does not mean that you would never want it. I think that I'd also have to disagree with the permise that encapsulation is only for hiding stuff that is just a convention of convenience. The main point of encapsulation is to hide information or functionality. If encapsulation is only used for the convenient breakdown of your primary functionality, then all of your primary functionality is public, package or protected. That does make it inheritable. But, now all of the primary functionality is a part of the contract for that class.
    Is there an answer to this issue that does not ignore the value of either encapsulation or inheritance?
    There is one way that I can see to do exactly what I think should be possible. That is to put only classes from the same hierarchy in a package. Then both package and protected effectively provide encapsulation with the ability to inherit (and you do still have the option to use private or final if there is a case where you want to disable inheritence).
    What I'd like to know is - What do people actually do? In the real world, do people:
    1) use private + cut and paste
    2) use package/protected + self discipline
    Where 2 is that you drop encapsulation within your package but then excercise self dicipline and just don't call/access stuff that you intend to be for that class only...
    Or is there some 3rd thing that I'm missing? I've tried to think how maybe you could design your objects in such a way that you'd never need to inherit/extend something that you would also want to encapsulate. But I just don't see how that's possbile.
    So, what do people do?
    Chris

    First of all, you have got to understand that I am not
    suggesting that Private and Final should be changed or
    removed from java. It looks to me like there should
    be an additional access option (and there was
    originaly).
    I understand that if a class inherits something, it
    could expand the access or put public accessor methods
    around it. Obviously with ultra sensitive code this
    would be a nightmare. So private and final are very
    important. But if the very possibility of another
    class expanding a given level of access is a reason
    for not even having that level of access, then why do
    we have package and protected?
    There are a great number of places in common coding where that access does restrict usage in a usable way.
    >
    If the only re-use of your code that you allow is
    through the public interface, what do you even need an
    OO language for? Just for the polymorphism and a
    different way to organize your code?
    Not sure what you mean by that but see below.
    But as I've said. I've seen this whole thing argued a
    number of times. But what I haven't seen is any
    explanation of what people who take the poslition that
    I'm taking actually do when they write code. Because
    I can sit here with a bunch of other people and say 'I
    wish Java had this or that'. And then of couse a
    bunch of people will resopond and say 'no that's dumb'
    or 'I don't see the point'. But at the end of the
    day, Java still is what it is. So, arguing about what
    it 'should be' is not going to effect how anyone
    codes.
    Sure it can. That is why java now has assert().
    So, what I started out wanting to know is how people
    actually code. Particularly people who wish that Java
    had a subclass only access modifier.
    I don't wish that.
    Perhapse I should also be asking about how things are
    done by people who see this level of access as
    unnececary. How they code is easy enough to
    understand. Making everything that is not intended to
    be accessed by any other class private is easy enough
    to do. But what would be interesting to know is how
    do you design your classes to leveradge inheritance if
    you do this. Maybe there is some way of desinging
    around ever having 'internal functionality' that you
    would want to extend and I'm just not getting it.
    There are three broad classifications of objects.
    1. Those that only use encapsulation
    2. Correct inheritence hierarchies
    3. Incorrect inheritence hierarchies
    The first of those, which I consider most classes to fall into, do not need this.
    The third area occurs when programmers use inheritence as a convenience mechanism to propogate behavior amoung different classes rather than using encapsulation as should be done. They don't understand the difference between "is-a" relationships (design) and coding convienence. I would estimate that at least 50% of existing object hierarchies fall into this area. Since in this case the entire design is wrong an extension is not needed.
    The second area is the only correct area where this might be needed. Since I personally believe that very few classes belong in hierarchies and this proposed extension would only be useful in a sub fraction of those. Since the correct usage is so small I don't think it would be useful addition to the language.

  • Override a private method in a Base class?

    How can a subclass override a final method in its superclass.
    This code compiles cleanly.
    How is this possible?
    Or Am I overlooking any point?
    class MySuperClass{
    private final String getMessage(){
         return "hello";
    protected String getAnotherMessage(){
         return getMessage() + "world";
    class MySubClass extends MySuperClass{
    private final String getMessage(){
         return "hi";
    public String getAnotherMessage(){
       return "anothermessage";
    }

    getMessage is declared as private in the base class, and therefor cannot be overridden in any subclass.
    Edit: I think I understand the question better now. You want to know why it compiles when you think it shouldn't. It's because the private method isn't really inherited at all. Your subclass created a brand new private method of the same signature, but it's completely unrelated.

  • Private attributes and Inheritance.

    I have a question regarding 'private attributes and inheritance'.
    If I have a class that will be extended by other classes,(basically
    this will act as a BASE class ),then why do I need to define
    any attribute private to this base class.?
    If I define an attribute as private in the base class,then the subclass cannot access
    this attribute.Right?
    1) Why define a private attribute in the base class ?
    2) When can a situation arise whereby the base class attribute is defined
    as 'private' and the base class is also extensible?

    If I define an attribute as private in the base
    class,then the subclass cannot access
    this attribute.Right?Right. A simple example would tell you this.
    >
    1) Why define a private attribute in the base class?Because information hiding and encapsulation are always good things, even between super and sub classes.
    >
    2) When can a situation arise whereby the base class attribute is defined
    as 'private' and the base class is also extensible?This question makes no sense whatsoever. A base class is extensible, unless it is marked as final, whether or not it's got private data members.
    Objects usually have private state and public interfaces. The idea is that clients of a class, even subclasses, should only access the private state thorugh the public interface. So if you've designed your classes properly you shouldn't need to access that private state.
    If you do, you can always provide get/set methods.
    OR declare the data members as protected. That way they're package visible and available to subclasses.
    But private members do not make a class inextensible.
    %

  • Extending classes with private methods?

    my understanding of extending classes is that you gain all the functions and methods of that class thus You could over ride any one of them. How ever I am confused on weather or not you inherit and can over ride private methods of the class you are extending or if you have to have all methods public in an extended class.
    hope that makes sense, an example can bee seen bellow.
    package
         public class Class1
              public function apples():void
                   //some code
              private fnctuin bananas():void
                   //more code
    package
         public class Class2 extends Class 1
              override public function apples():void
                   //i changed code
              //can I over ride bananas?

    you can only override methods that would be inherited.  a private method won't be inherited:
    http://www.kirupa.com/forum/showthread.php?223798-ActionScript-3-Tip-of-the-Day/page5

  • Call Enterprise Bean (or Database) from private Method in Session-Bean

    Hi Everybody,
    I've a question regarding the possibility to call an dependency injected EJB in an private method of a session bean.
    Imagine the following.
    @Stateless
    public class SomeBean implements SomeLocal{
       @EJB
       private AnotherLocal anotherBean;
       /** Will be called from a web-app via delegate layer */
       @TransactionAttribute(TransactionAttribute.RequiresNew)
       public void someBusisnessMethod(){
           String something = this.getSomeThing();
           //Do more
       private String getSomeThing(){
          return anotherBean.aMethodWhichCallsTheEntityManager();
    }I've to refactor code with uses such Call-Hierachy and I want to know whether this is a correct way? Somebody told me that such stuff should not be made, and I quess he told me an explanation, why not to do such stuff, but unfortunally I've forgotten that. Do someone have a suggestion why not to do this? Could it blow the application to hell? Is there any difference to the following code (The way I would have done it)?
    @Stateless
    public class SomeBean implements SomeLocal{
       @EJB
       private AnotherLocal anotherBean;
        @Resource
        private SessionContext sessionContext;
       /** Will be called from a web-app via delegate layer */
       @TransactionAttribute(TransactionAttribute.RequiresNew)
       public void someBusisnessMethod(){
           SomeLocal self = this.sessionContext.getBusinessObject(SomeLocal.class);
           String something = self.getSomeThingBusinessMethod();
           //Do more
       @TransactionAttribute(TransactionAttribute.Required)
       public String getSomeThingBusinessMethod(){
          return anotherBean.aMethodWhichCallsTheEntityManager();
    }

    Found the answer by myself....
    Here it is if someone might have the same question:
    http://stackoverflow.com/questions/3381002 or if the link may down sometime the content of the answer...
    >
    The motivation here is that most EJB implementations work on proxies. You wouldn't be too far off in thinking of it as old-school AOP. The business interface is implemented by the EJB container, quite often via a simple java.lang.reflect.Proxy, and this object is handed to everyone in the system who asks for the ejb via @EJB or JNDI lookup.
    The proxy is hooked up to the container and all calls on it go directly to the container who will preform security checks, start/stop/suspend transactions, invoke interceptors, etc. etc. and then finally delegate the call to the bean instance -- and of course do any clean up required due to any exceptions thrown -- then finally hand the return value over through the proxy to the caller.
    Calling this.foo() directly, or passing 'this' to a caller so they can make direct calls as well, will skip all of that and the container will be effectively cut out of the picture. The 'getBusinessObject(Class)' method allows the bean instance to essentially get a proxy to itself so it can invoke its own methods and make use of the container management services associated with it -- interceptors, transaction management, security enforcement, etc.
    written by David Blevins

  • Calling a private method

    class A{
         private void x(){
              System.out.println("x of A") ;
         void y(){
              System.out.println("y of A") ;
    class B extends A{
         private void x(){
              System.out.println("x of B") ;
         void y(){
              System.out.println("y of B") ;
         void xy(){
              x() ;
              y() ;
    class Demo{
         public static void main(String[] args){
              B b1 = new B() ;
              b1.xy() ;
    o/p :
    x of B
    y of B
    class A{
         private void x(){
              System.out.println("x of A") ;
         void y(){
              System.out.println("y of A") ;
         void xy(){
              x() ;
              y() ;
    class B extends A{
         private void x(){
              System.out.println("x of B") ;
         void y(){
              System.out.println("y of B") ;
    class Demo{
         public static void main(String[] args){
              B b1 = new B() ;
              b1.xy() ;
              A b2 = new B() ;
              b2.xy() ;
              A a = new A() ;
              a.xy() ;
    o/p :
    x of A
    y of B
    x of A
    y of B
    x of A
    y of A
    anyone plz explain the concept, how method x is called in abve 2 cases?????
    thnx in advance.....
    Edited by: rits on Sep 5, 2008 3:25 AM

    Basically... this is using inheritance. The output shows which methods are/are not inherited from the superclass.
    I'll edit this post after submitting it, and try to explain some concepts, then you should look at your code and try to figure it out.
    First example
    class Demo{
         public static void main(String[] args){
              B b1 = new B() ;
              b1.xy() ; //Calls xy() method in B, and the xy() method calls x() and y()
    Second example
    class Demo{
         public static void main(String[] args){
              B b1 = new B() ;
              b1.xy() ; //calls the method xy() in B [which is actually inherited from A], xy() method calls x() and y()
                   // the x() method is not inherited [private], so the one in A is used
                   // the y() method is inherited from A and is used here
              A b2 = new B() ;
              b2.xy() ; //calls the xy() method in A
                   // this is a little bit tricky though, as the label is of type A (the superclass), but the actual class is B
              A a = new A() ;
              a.xy() ; //calls the xy() method in A
                   // note that B is not used at all here
    }But I'm reasonably new to this, and this isn't really straightforward, so I'd recommend waiting for someone else to confirm that I'm right before you try to understand what I'm saying ;)
    Edited by: shano on Sep 5, 2008 3:50 AM

  • Enum private methods: did everyone know this but me?

    Consider the following code:class C {
        final C C1 = new C() {
            public void f() {
                g();
        private void g() {
    enum E {
        E1 {
            public void f() {
                g();
        private void g() {
    }It struck me that the class and the enum are structurally very similar: the class has an inner class that references a private method; the enum has a value that references a private method.
    But the big difference is: the enum won't compile. Unless I change the protection on g() to "protected" or less, it throws an error.
    And the bizarre part is, the error is not "g has private access" or "cannot find symbol". No, it's "non-static method g() cannot be referenced from a static context"! WTF?
    I solved the mystery by utter accident, when I changed the class to class C {
        static final C C1 = new C() {
            ...That is, I made the variable referring to the instance of the inner class static. That made the class fail to compile with the same "static context" error I saw in the enum.
    It took several minutes of open-mouth staring at the screen to get it: in the original class, the g() being called was not in the same object, but in the outer object. Methods of object declared in a derived class cannot get to private members, even of the same object, declared in an ancestor class: that is the meaning of the word "private". But methods of an inner class can get to private members of the outer class. So in the original class, the inner-object could not see its own g(), so it looked at the outer-object's g(); when I changed the inner-object to static, there was no outer object, and I got an error to that effect.
    Enum values are basically solitary instances of static inner classes of the class representing the enum itself and so, in the same situation produce the same error message.
    Oddly, the following does compile:enum E {
        E1 {
            public void f() {
                E1.g();
        private void g() {
    }That is, instead of accessing g() as E.this.g(), I accessed it statically as E.E1.g(). In fact, this was the first thing I tried -- under the wrong impression that f() was static within E1, not the E1 was static within E. In retrospect, I can see why it works, but I cannot explain it properly or defend it intellectually.
    Who sez Java ain't fun?
    M.

    It took several minutes of open-mouth staring at the
    screen to get it: in the original class, the g()
    being called was not in the same object, but in the
    outer object. Methods of object declared in a
    derived class cannot get to private members, even of
    the same object, declared in an ancestor class: that
    is the meaning of the word "private".There's a problem with this theory. Consider the following:
    class C {
        protected String s = "C";
        public static final C C1 = new C() {
            public void f() {
                s = "C1";
                C.C1.g();
        private void g() {
            System.out.print(s);
        public void f()
            System.out.println("C.f()");
    }Then a main method like so:
        public static void main(String[] args) {
            try {
                C.C1.f();
            } catch (Exception exception) {
                exception.printStackTrace();
    output:
    [pre]
    C1This can be changed to:
        public static final C C1 = new C() {
            public void f() {
                s = "C1";
                ((C)this).g();
        };To acheive the same effect. You can make C1 an instance, but you cannot run the example because it will throw a StackOveflow exception.
    So to run the original example, we have to Change C to:
    class C {
        static int count;
        protected String s = "C";
        public C()
            if (count++ < 2) C1 = new C() {
                public void f() {
                    s = "C1";
                    ((C)this).g();
            else C1 = null;
        public final C C1;
        private void g() {
            System.out.print(s);
        public void f()
            System.out.println("C.f()");
    }now the main body becomes:
    new C().C1.f();Output:
    C1So the point is that the method is not called on the outer instance. The problem is with access and how the compiler is creating the code to fuflill the syntactic sugar of inner classes and nested classes.
    One rule says the subclass doesn't have access to call the g() method defined in the parent class. The other rule says that it does because it's an inner class. So C1 can call g() on a C instance but not on an instance of it's anonymous class. This is a contradiction as the anonymous class instance is a C. Whether this follows the JLS (therefore not a bug) I think it's still a flaw. Try casting C1 to a C in the enum example and see if it resolves the issue.

  • How to access the private method

    All,
    I have class ABC with private method getfilename().
    I want to use this private method ...
    Is it possible to use this method without inheritence ?
    Is it possible to access this private method using annoymous inner class ?
    or any other alternatives ??
    namanc

    I have class ABC with private method getfilename().
    I want to use this private method ... You can't; it's private to the instantiations of that class.
    Is it possible to use this method without inheritence ? No, no even with inheritance.
    Is it possible to access this private method using
    annoymous inner class ? Nope, unless you can write that anonymous inner class yourself.
    or any other alternatives ?? Nope; privvy parts are privvy parts and only the owner of those privvy
    parts can touch them. (ahem)
    kind regards,
    Jos
    ps. unless you want to do reflection surgery of course.

  • How to call a private method in a JFrame

    I have a Frame which has some properties like its size, bgcolor plus other parameters, as instance variables. There is a button on the Frame with the caption : "set properties". When one clicks on that button, a new frame should appear via which a user can change the values of the parameters of the main Frame (i.e size, bgcolor,..etc). The user would input the new values in the textfields or radio buttons that are on the new frame, and then click a submit button, which has to exist on the same NFrame. How can I do that so that when the submit button is pressed, the parameters values are updated and so is the display view ?
    I made it this way : I created 2 classes, the main frame and the new Frame. I made the new Frame an instance variable of the main Frame. When the user clicks the " set properties" button on the main Frame, the new Frame is shown. The user enters new values for some of the parameters and clicks submit. The parameters in the new Frame are updated. UP TO HERE EVERYTHING WENT JUST FINE. Now, there is a private method in the main frame that changes the color, size, ...etc of the main frame according to the values stored in the instance variables color, size,...etc. THE QUESTION IS: How can the new Frame display the changes after the values have been updated ? That is, how can it call the "private" method in the main class?? Should the new class be a child class of the main class to be able to access it's private methods ??

    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class CallingHome
        SkinMod skinMod;
        JPanel panel;
        public CallingHome()
            // send reference so SkinMod can call methods in this class
            skinMod = new SkinMod(this);
            JButton change = new JButton("change properties");
            change.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    skinMod.showDialog();
            JPanel north = new JPanel();
            north.add(change);
            panel = new JPanel();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(north, "North");
            f.getContentPane().add(panel);
            f.setSize(300,100);
            f.setLocation(200,200);
            f.setVisible(true);
        public void setBackground(Color color)
            panel.setBackground(color);
            panel.repaint();
        public static void main(String[] args)
            new CallingHome();
    class SkinMod
        CallingHome callHome;
        Random seed;
        JDialog dialog;
        public SkinMod(CallingHome ch)
            callHome = ch;
            seed = new Random();
            createDialog();
        public void showDialog()
            if(!dialog.isShowing())
                dialog.setVisible(true);
        private void createDialog()
            JButton change = new JButton("change background");
            change.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    callHome.setBackground(getColor());
                    dialog.dispose();
            JPanel p = new JPanel();
            p.add(change);
            dialog = new JDialog();
            dialog.getContentPane().add(p);
            dialog.setSize(200,100);
            dialog.setLocation(525,200);
        private Color getColor()
            return new Color(seed.nextInt(0xffffff));
    }

  • Error while usind Private Method of a global class

    HI All..
    I created a global class (ZLINE_GLOBAL) which has TOT_DATA private method. I have to call this private method in my report, I know that using Friend class we can do this.
    But it is not working and showing the same error  "  METHOD "TOT_DATA" is unknown or Private or Public..
    code i tried is
    CLASS c2 DEFINITION DEFERRED.
    CLASS ZLINE_GLOBAL DEFINITION FRIENDS c2.
      PUBLIC SECTION.
        METHODS : m1.
      PRIVATE SECTION.
        METHODS: m2.
    ENDCLASS.
    CLASS ZLINE_GLOBAL IMPLEMENTATION .
      METHOD m1.
        WRITE : 'Public Method C1'.
      ENDMETHOD.                    "M1
      METHOD m2.
        WRITE : 'Private Method C1'.
      ENDMETHOD.
    ENDCLASS.
    CLASS c2 DEFINITION FRIENDS ZLINE_GLOBAL.  "my friends are here, allow them access to my (C2's) private components
      PUBLIC SECTION.
        METHODS :m3.
    ENDCLASS.
    CLASS c2 IMPLEMENTATION.
      METHOD m3.
        DATA : obj TYPE REF TO ZLINE_GLOBAL.
        CREATE OBJECT obj.
        CALL METHOD obj->TOT_DATA.    "here Iam calling Private method of global class
      ENDMETHOD.                    "M3
    ENDCLASS.
    START-OF-SELECTION.
      DATA obj_c2 TYPE REF TO c2.
      CREATE OBJECT obj_c2.
      obj_c2->m3( ).
    can anybody help me on this..
    Murthy

    Hi Murthy,
    Replace TOT_DATA with M2, you do not have any method by name "TOT_DATA" in your code.
    CLASS c2 DEFINITION DEFERRED.
    CLASS ZLINE_GLOBAL DEFINITION FRIENDS c2.
      PUBLIC SECTION.
        METHODS : m1.
      PRIVATE SECTION.
        METHODS: m2.
    ENDCLASS.
    CLASS ZLINE_GLOBAL IMPLEMENTATION .
      METHOD m1.
        WRITE : 'Public Method C1'.
      ENDMETHOD.                    "M1
      METHOD m2.
        WRITE : 'Private Method C1'.
      ENDMETHOD.
    ENDCLASS.
    CLASS c2 DEFINITION FRIENDS ZLINE_GLOBAL.  "my friends are here, allow them access to my (C2's) private components
      PUBLIC SECTION.
        METHODS :m3.
    ENDCLASS.
    CLASS c2 IMPLEMENTATION.
      METHOD m3.
        DATA : obj TYPE REF TO ZLINE_GLOBAL.
        CREATE OBJECT obj.
        CALL METHOD obj->M2.    "here Iam calling Private method of global class
      ENDMETHOD.                    "M3
    ENDCLASS.
    START-OF-SELECTION.
      DATA obj_c2 TYPE REF TO c2.
      CREATE OBJECT obj_c2.
      obj_c2->m3( ).
    Regards,
    Chen

  • Creation of a static class with private methods

    I'm new to java programming and am working on a project where I need to have a static class that does a postage calculation that must contain 2 private methods, one for first class and one for priority mail. I can't seem to figure out how to get the weight into the class to do the calculations or how to call the two private methods so that when one of my other classes calls on this class, it retrieves the correct postage. I've got all my other classes working correct and retrieving the information required. I need to use the weight from another class and return a "double". Help!!!
    Here's my code:
    * <p>Title: Order Control </p>
    * <p>Description: Order Control Calculator using methods and classes</p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: Info 250, sec 001, T/TH 0930</p>
    * @author Peggy Blake
    * @version 1.0, 10/29/02
    import javax.swing.*;
    public class ShippingCalculator
    static double firstClass, priorityMail;
    //how do I get my weight from another class into this method to use??? not sure I understand how it works.
    public static double ShippingCalculator(double weight)
    String responseFirstClass;
    double quantity, shippingCost;
    double totalFirstClass, firstClass, priorityMail, totalShipping;
    double priorityMail1 = 3.50d;//prioritymail fee up to 1 pound
    double priorityMail2 = 3.95d;//prioritymail fee up to 2 pounds
    double priorityMail3 = 5.20d;//prioritymail fee up to 3 pounds
    double priorityMail4 = 6.45d;//prioritymail fee up to 4 pounds
    double priorityMail5 = 7.70d;//prioritymail fee up to 5 pounds
    quantity = 0d;//ititialization of quantity
    // weight = 0d;//initialization of weight
    // shippingCost = 0d;
    //calculation of the number of items ordered..each item weights .75 ounces
    quantity = (weight/.75);
    if (quantity <= 30d)
    //add 1 ounce to quantities that weigh less than 30 ounces
    weight = (weight + 1);
    else
    //add 2 ounces to quantities that weigh more than 30 ounces
    weight = (weight + 2);
    if (weight > 80d)
    //message to orderclerk ..order over 5 lbs, cannot process
    JOptionPane.showMessageDialog(null, "Order exceeded 5 lbs, cannot process");
    //exit system, do not process anything else
    System.exit (0);
    else
    if (weight < 14d)
    //send message to customer: ship firstclass or priority, y or n
    responseFirstClass = JOptionPane.showInputDialog(null, "Ship first class? y or n?");
    if (responseFirstClass.equals("y"))
    //compute FirstClass shipping cost
    totalFirstClass = ((weight - 1) * .23d) + .34d;
    firstClass = totalFirstClass;
    else
    //compute PriorityMail cost for orders less than 14 ounces
    priorityMail = (priorityMail1);
    else
    if (weight <=16d)
    //compute totalshipping for orders up to 16 ounces
    priorityMail = (priorityMail1);
    else
    if (weight <=32d)
    //compute totalshipping for orders up to 32 ounces
    priorityMail = (priorityMail2);
    else
    if (weight <=48d)
    //compute totalshipping for orders up to 48 ounces
    priorityMail = (priorityMail3);
    else
    if (weight <= 64d)
    //compute totalshipping for orders up to 64 ounces
    priorityMail = (priorityMail4);
    else
    //compute totalshipping for orders up to 80 ounces
    priorityMail = (priorityMail5);
    priorityMail = 0d;
    firstClass = 0d;
    firstClassMail ();
    priorityMailCost ();
    //I think this is where I should be pulling the two methods below into my code, but can't figure out how to do it.
    shippingCost = priorityMail + firstClass;
    return (shippingCost);
    }//end method calculate shipping
    private static double firstClassMail()//method to get first class ship cost
    return (firstClass);
    }//end method firstclass shipping
    private static double priorityMailCost()//method to get priority mail cost
    return (priorityMail);
    }//end method priorityMail
    }//end class shipping calculator

    public class A {
    public String getXXX () {
    public class B {
    A a = new A();
    public void init () {
    a.getXXX();
    }

  • Private methods Importing parameter cannot be changed error

    Hi Guys,
    I have this scenario where I have a private method inside a class which is having an error "Field SAPMF02K cannot be changed".
    here is the code for the private method call.
        call method create_bdc_dynpro
             importing  IM_PROGRAM = 'SAPMF02K'
                        IM_DYNPRO = '0100'.
    code of the method
      data: wa_bdcdata type bdcdata.
      CLEAR wa_bdcdata.
      wa_bdcdata-program = im_program.
      wa_bdcdata-dynpro = im_dynpro.
      wa_bdcdata-dynbegin = at_true.
      APPEND wa_bdcdata to at_bdcdata.
    Hope you can help
    Thanks!

    Howdy,
    I think you have your importing/exporting the wrong way round.
    The method call should be:
    call method create_bdc_dynpro
    exporting IM_PROGRAM = 'SAPMF02K'
    IM_DYNPRO = '0100'.
    And of course in the method definition they should be importing parameters.
    Cheers
    Alex

  • ABAP Objects: Calling private Methods

    Hi,
    i would choose an private Method of an global class (for example class: CL_GUI_ALV_GRID private Method: SEARCH_START) in a local class.
    class lcl_test definition for testing.
      private section.
        methods test for testing.
      data ref_alv type ref to cl_gui_alv_grid.
    endclass.
    class lcl_test implementation.
      method for test.
        create object ref_alv ...
    * How to call a private Method?
    call method ref_alv->search_start( ). "not possible!   
      endmethod.
    endclass.
    Is this possible?
    Regards,
    Damir

    Damir, of course you can call a private method of a class, if this class has made you a friend with the syntax element FRIENDS (available since Release 6.10). Here is a syntactically correct example, when my_method is a private class method:
    REPORT test.
    CLASS mytest DEFINITION FOR TESTING.
      PRIVATE SECTION.
        METHODS test FOR TESTING.
    ENDCLASS.
    CLASS myclass DEFINITION FRIENDS mytest.
      PUBLIC SECTION.
        CLASS-METHODS my_method.
    ENDCLASS.
    CLASS myclass IMPLEMENTATION.
      METHOD my_method.
      ENDMETHOD.
    ENDCLASS.
    CLASS mytest IMPLEMENTATION.
      METHOD test.  
        CALL METHOD myclass=>my_method.
      ENDMETHOD.
    ENDCLASS.
    If my_method is not a class method, then you need to create an object of the class first, whose methods you want to test.
    Kind regards,
    Michael Kraemer

Maybe you are looking for