Private final method

When can we use private final method. Could you please give some detail explanation
Thanks

Did you look at the output? No, I did never execute the code, and I didn't even
look at the code that much (as you can see from my
previous post)Sorry. I was posting while you were continuing to reply.
I found that if I put this in B I get a compile error.
public static void main(String[] args){
    A b = new B();
    System.out.println(b);
    System.out.println(b.isFoo());//this surprises me
A.java:27: isFoo() has private access in A
    System.out.println(b.isFoo());//this surprises meWhich is still puzzling to me somehow. What happened to B isFoo in this case? I didn't think that referencing by the supertype would have worked like this.

Similar Messages

  • Actual Benefits of final methods and final parameters

    I know that a lot of this depends on the JVM and the actual code, but I was wondering what the actual real world advantage was of using final methods and final parameters.
    I use a business and data layer for my program to interact with the database. So all of the methods in these classes are public and static. I was just wondering if it would be benefical to make all of these methods final and all of the parameters final also. I won't ever be making subclasses of these classes, so is this worth doing?
    Thanks,
    Dave Johansen

    On the point of final, this should always be a design decision. That is, does it make sense to allow your class to be overridden? Making classes and/or methods final is a big barrier to future enhancements and extendability - so only make soemthing final if you haver a specific reason for doing so.
    Any performance issues should not take a high precedence in this decision - and in any case the difference in making something final will be non-existant for all practical purposes.
    How about volatile?
    I get the meaning of synchronized but
    volatile?Volatile is a keyword that tells the JVM it can't optimize / inline serctions of code that use certain variables. You may not realise it, but the JVM takes your bytecode and chops them up and re-arranges them at runtime, to boost performance. This can sometimes have dangerous consequences in a mutlithreaded environment, so by adding the volatile keyword you are saying to the JVM (or specifically HotSpot) not to perform any "code magic".
    Here's a simple example:
    public class TestClass {
        private boolean check = false;
        public void setTrue(){
            check = true;
        public void check(){
            check = false;
            if(check){
                System.out.println("Will this ever print?");
    }Obviously the string will never print in a single threaded environment. However, in a multithreaded environment, is is possible that a thread could call setTrue() between another thread setting the value to false and performing the if() check. The point is that due to runtime optimization, Hotspot may realise that check is always false, so completely remove the code section with the if block. so regardless of the value of the boolean, the code may never be entered.
    One solution is to declare the boolean check as volatile. This tells the JVM that such optimizations are not allowed and then it is entirely possible for the string to be printed.
    One curiousity, off-topic:
    is there a way for jvms instantiations to see each
    other?Have you looked into RMI?

  • Final Method Parameters

    I've discovered I don't understand final method parameters as I thought I did. The language spec says you can declare a parameter as final, which I would have thought meant the method can't change it. But it turns out the called method can change it. In the following code, the change() method modifies the Test parameter quite easily.
    What am I misunderstanding here? If final doesn't keep the parameter from being modified, what does it do?
    public class Test
    private int privateValue = 0;
    * Stores the private value.
    * @param privateValue The value to store.
    public void setPrivateValue(int value)
       privateValue = value;
    public static void change(final Test test)
       test.setPrivateValue(3);
       test.setPrivateValue(4);
    * Program entry point
    * @param args Command line arguments
    public static void main(String[] args)
       Test test = new Test();
       Test.change(test);
       System.out.println("Done");
    }

    "Ahh, I see," said the blind carpenter, as he picked up his hammer and
    saw. I was indeed misunderstanding the use of final. It doesn't protect the
    reference object from changes, only the reference variable itself. Sigh...Just to be sure, is this your way of saying "I don't understand those explanations"?
    Look closely now :-)
    public class Test
    private int privateValue = 0;
    public void setPrivateValue(int value)
       privateValue = value;
    public static void change(final Test test)
       test.setPrivateValue(3); //this line does not even attempt to change the variable's value
       test.setPrivateValue(4); //neither does this one
      //incidentally and irrelevantly, they do ultimately change the value of another variable; a private field of the object pointed to by "test"
       //the next line DOES attempt to change the variable's value
       test = new Test(); //this does not compile because test is declared final
       test = null; //and again!
    public static void main(String[] args)
       Test test = new Test();
       Test.change(test);
       System.out.println("Done");
    }Variables (and parameters) hold primitives or references (they do not hold objects). For reference variables, they are either null or they point to an object. "final" applies to variables, not to the objects they may point to.
    If final
    doesn't keep the parameter from being modified, what
    does it do?So (I hope) you see, it does just that, generate a compile time error when the parameter is being modified.
    What am I misunderstanding here?I don't know. That's exactly what everyone else said.

  • Static final method decleration...

    Hello
    I'm confused with >>>static final<<< method decleration.
    final is used for methods to make them nonoverridable for the extender classes. when the method is declared as static, it is also nonoverridable, too.. so why the static final is allowed?
    It's too confusing, i think..

    alphabet,
    I'm confused with >>>static final<<< methodYeah, I found it all a bit confusing to start with... especially coming from a C background where "static" also has several meanings, which are similar but not the same as in java.
    However, I now use the "final static" syntax religiously... to explicitly state "this is a static method and it cannot be overridden", coz I reckon it'll be less confusing for newbies, who don't necessarily know that static can't be.
    To be explicit, I also use "public $method" in interfaces.
    In fact, I reckon it would have improved java, if they had made the compiler always require an explicit scope modifier (private, protected, public), an explicit (static, instance), and an explicit (constructor, final, overridable)... as in:protected class myClass {
      protected instance constructor myClass() {
        super();
    }keith.

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • 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

  • Urgent pls-AdapterActivatorPOA overrides final method Error

    I am getting the following error when trying to access our reports .jsp files.
    java.lang.VerifyError: class org.omg.PortableServer.AdapterActivatorPOA overrides final method .
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:537)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.evermind.util.OC4JSecureClassLoader.defineClassEntry(OC4JSecureClassLoader.java:172)
    etc. . .
    No solutions forthcomming on the web and we have tried everything we can think of. Is this perhaps a java version problem. Seems that 9.0.4 is running java version 1.4.2. We have a staging area with a 9i server. It runs fine (java version 1.3).
    Also of note is that reports test implementation works fine. If we move our files to this location the reports come up. No graphs are displayed but the data is there and no error comes up.
    As a note we have replaced the reports_tld.jar in the ear with the one from the test area and redeployed with no changes (error returns).
    Any explination would be appreciated.
    Rhys Parry

    Hi,
    You need to check the Sampling procedure in QDV2 T-code
    In assignments check for which sampling type and valuation mode you had selected.Becuase you might choosed a valuation type which does not support control chart type.But for MIC you might ticked the chart type in control indicator.
    Manoj.N

  • Final method and final class

    What is final method and final class in abap objects.

    ejp wrote:
    Since that doesn't work--or would overyy complex to implement... would be impossible to implement. Once the method-local copy goes out of existence, ipso facto it can never be changed. This is the whole point.I consider it impossible too, but I'm not a language/compiler/runtime expert, so I allowed for the possibility that there could be some way to do it--e.g. local variables that are references in inner classes live on the heap instead of the stack, or something. My point isn't that it's possible, just that if it were somehow to be done, it would by ugly, so we may as well consider it impossible--it just ain't gonna happen.
    we go with the logic, "Okay, we need to copies, but keeping them in sync is a nightmareNo, it is +meaningless.+No, it's not meaningless. If we have the two copies, and they're not final, then after the inner object is created, the method can continue running, and either the method or the inner object could modify its copy. As far as our code knows, it's the same variable, so there'd have to be some way to keep them in sync. That's either impossible or undesirably complex--like the above, it doesn't matter which--so it's final in order to get past the issue of keeping the copies in sync.

  • Why do we need private static method or member class

    Dear java gurus,
    I have a question about the use of private and static key words together in a method or inner class.
    If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
    Could anybody help me to clear this.
    Thanks,

    What don't you get? Private does one thing, andstatic does >something completely different.
    If you want to listen to music, installing an airconditioner doesn't help>
    Hi, if the private keyword is the airconditioner, do
    you think you could get music from the static keyword
    (it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
    Private does one thing. If you want that thing, use private.
    Static does something completely different and unrelated. If you want that thing, use static.
    If you want both things, use private static.
    What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

  • Discussion: private final static vs public final static

    take following class variable:public final static int constant = 1;Is there any harm in making this variable public if it's not used (and never will be) in any other class?
    Under the same assumption Is there any point in making this variable static?
    tx for your input

    Is there any harm in making this variablepublic
    if it's not used (and never will
    be) in any other class?Harm? No. Use? Neither.I suppose it makes no difference at all concerning
    runtime performance?
    Under the same assumption Is there any point inmaking this variable
    static?If the creation of the constant is costly, for
    instance. A logger is private final static most of
    the time.Same here, does making a variable final or static
    have any influence on runtime performance?No. And for 'expensive' operations (say, parsing a XML configuration file, which only needs to occur once), making a variable static will improve performance.
    - Saish

  • What is the use of private static method/variable?

    Hi All,
    I have read lots of books and tried lots of things but still not very clear on the
    topic above.
    When exactly do we HAVE to use private static methods?
    private implies its only for class, cannot be accessed outside.
    But then static means, it can be accessed giving classname.method.
    They seem to be contradicting each other.
    Any examples explaining the exact behaviour will be well appreciated.
    Thanks,
    Chandra Mohan

    Static doesn't really "mean" that the method/field is intended for use outside the class - that is exactly what the access modifier is for.
    Static implies that it is for use in relation to the class itself, as opposed to an instance of the class.
    One good example of a private static method would be a utility method that is (only) invoked by other (possibly public) static methods; it is not required outside the class (indeed, it might be dangerous to expose the method) but it must be called from another static method so it, in turn, must be static.
    Hope this helps.

  • Private static method

    How do I get access to a private static method of a class?
    I can't just call it by object.privatemethod() , right?

    unless your call is made within the body of the
    class, you cannot call it, otherwise just call it via
    a static ref of the class
    ObjectName.privateMethod()
    (not)
    ObjectInstance.privateMethod()...where "ObjectName" is the name of the class.
    Or you can just call it with privateMethod(), but that tends so suggest "this.privateMethod()" so I'd go with qualifying it with the class name, to be clear.

  • Private instance method

    I want to have a private instance method in my application that changes the values of some variables. Then I want to use these variables in the main method. Is it possible to do this?
    When I tried to do it, I recieved the following error message:
    non-static variable cannot be accessed in static context
    Can anybody help me?

    import java.util.*;
    public class Test {
      public static void main(String[] args) {
        Test test = new Test();
        test.showData();
        test.setMyString("xyz");
        test.setMyInt(55);
        System.out.println("Main1 - myInt="+test.getMyInt()+", myString="+test.getMyString());
        test.mungeData();
        System.out.println("Main2 - myInt="+test.getMyInt()+", myString="+test.getMyString());
      private int myInt = 3;
      private String myString = "abc";
      public Test() { }
      public String getMyString() { return myString; }
      public void setMyString(String s) { myString = s; }
      public int getMyInt() { return myInt; }
      public void setMyInt(int i) { myInt = i; }
      public void mungeData() { myInt++; myString+="x"; }
      public void showData() { System.out.println("Test - myInt="+myInt+", myString="+myString); }
    }

  • Whether private getter methods is Evil?

    Hi!
    I was wondering whether it is bad or good to use private getter methods in a class rather than directly accessing private fields?
    For instance, I have a getter method for each Swig component used in my program:
        private JButton run;
        private JButton getRun() {
             if (run != null) {
                  return run;
            run = new JButton("Run");
            run.setToolTipText("Run");
            run.setIcon(new ImageIcon(ResourceHelper.getImageResource("run.png")));
            run.setEnabled(false);
            run.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    MessageDialog.showPleaseWait(TestRunnerUI.this,
                        "creating logger", new Runnable() {
                            public void run() {
    // bla bla bla
            return run;
        }And so for each swing component....
    But for example I have such a method:
        private void disconnect() {
            mRunner = null;
            mLogger = null;       
            log.log(Logger.INFO, "disconnected");
            tree.setModel(defaultModel);
            tree.setEnabled(true);
            save.setEnabled(false);
            saveAs.setEnabled(false);
            load.setEnabled(false);
            options.setEnabled(false);
            run.setEnabled(false);
            breakTests.setEnabled(false);
            connect.setEnabled(true);
            disconnect.setEnabled(false);
        }which changes properties of a lot of components...
    I don't know whether I should use there private getter methods or not. From the design perspective it seems I should but it also adds some overhead I suppose...

    I use accessor methods when writing persistent
    classes and javabeans. The key is not to use them by
    default, only when required. IMO this does not
    violate encapsulation, it hides implementation. Agree. Inside the bean itself you shouldn't use it's accessors either.
    The
    main benefit being that should you need to refactor
    the way a value is retrieved or set you have
    localized the changes. Holub will tell you that if
    you are using an accessor method to retrieve a value
    from an object, in order to do some computation on
    that value, you should move the computation into the
    object's class instead (hence "getter and setter
    methods are evil").Summarized, the public accessors are evil when the code behind does not only return/set the encapsulated value. Solution: refactor, split and rename them to "createSomething", "lookupSomething", "buildSomething", or so.
    In this case the topicstarter was talking about private getters tho.

  • Forcing invocation of private/protected methods

    Has anyone, any idea how can be forced the invocation of a private/protected method on a object. The client that invokes the method has a reference to the object and is declared in a different object than the targeted object.
    See code below:
    package src.client;
    import java.lang.reflect.Method;
    import src.provider.CPBook;
    public class Tester {
         public static void main(String [] args) {
              CPBook targetObj = new CPBook();
              Method [] mths = targetObj.getClass().getDeclaredMethods();
              Method targetMth = null;
              for (int i = 0; i < mths.length; i++) {               
                   if ("getMgr".equals(mths.getName())) {
                        targetMth = mths[i];
              if (targetMth != null) {
                   try {
                        Object [] obj = new Object[1];
                        obj[0] = new Boolean(true);
                        targetMth.invoke(b, obj);
                   } catch (Exception e) {                    
                        e.printStackTrace();
    package src.provider;
    public class CPBook {
         public void startDownload() {                    
         public void stopDownload() {     
         protected void getMgr(boolean bool) {
              System.out.println("------- OK ------- : " + bool);
    }Thank you.
    Best regards.

    The class java.lang.reflect.Method has a setAccessible(boolean) method on it. I think that's what you're asking for. Code that makes use of it might run into trouble if a security manager is involved, though. Generally, methods are private for a reason, too, so if your code depends on a private method, it's dependent on an implementation detail it probably shouldn't be concerned about, or even aware of

Maybe you are looking for

  • My iPad cannot find my HP AirPrint printer HP 3050 .  We are on the same network

    I have recently converted all our family devices to Apple.  My Mini-Mac has found my printer as well as my Mac Air.  The only device that has not is my wife's iPAD.  She is on the same home network as my other systems, but no results.  Software updat

  • Messages (Jabber) Refuses to Authenticate AD Users after 10.9.2/Server 3.0.3 update

    Once again, an update appears to have broken Messages/Jabber's ability to authenticate AD users after the 10.9.2/Server 3.0.3 update even though it was working well before. Hoping someone here has some ideas for how to help! I can log in just fine as

  • Purchased items from ipod won't sync to computer

    I bought a ton of music on my ipod from the itunes store. I just got an iphone, so I'm trying to transfer my purchased songs from my ipod to my itunes computer library so I can put them on my iphone, but the purchased items won't sync.

  • Defined customs tariff value(pricing)

    Dear all i am posting this for second time during import process for some materials basic custom duty is on tariff value. i.e if the material price is 1000 dollars BCD will be on 700 dollars only . how to map this in pricing procedure right now what

  • Help! Can't drag Widgets to use them.

    I have some standard Widgets in the Library/Widgets folder and one third party Widget in my user/mummer/library/widgets folder. When I activate Dashboard, and try to add Widgets, they all show up in the bar across the bottom. I can drag the third-par