Question about static method hiding

I undestand that a static method may only be hidden in a subclass not overridden. But, I don't understand why an exception type thrown by the subclass method must be a subtype of the exception type thrown by the superclass method. For example,
public class A {
public static void foo() throws ExceptionA { }
public class B extends A {
public static void foo() throws ExceptionB { }
gives a compile-time error if ExceptionB is not a subclass of ExceptionA. This makes perfect sense in the non-static case but what does it matter here?
Thanks,
Tim

I don't understand your point. In either case, static
or non-static, ExceptionB must be the same or a
subclass of ExceptionA. My question is why this
matters in the static case.I think it's for binary compatibility, that is, so that you can make changes to Java source files and recompile only the changed files. If you originally did not have the static method in class B, and called B.foo() in another class, the A.foo() method would actually be called at run time. If you then change the B class and add a foo() method, it must be compatible so that the other class's method call is still valid.
If you're unfamiliar with the concept of binary compatibility, read the chapter in the Java Language Specification. It's a critical but often overlooked aspect of the Java language.

Similar Messages

  • A basic question about static variables and methods

    What would be the effects if I declare lots of static variables and static methods in my class?
    Would my program run faster?
    Would the class take more memory spaces? (If so, how do I estimate an appropriate number of variabls and methods to be declared static?)
    Thank you @_@

    when you declare a static var the var isn't created for every instance of the class, it just "live" in the class
    when you declare a static method is the same, so if you have:
    class MyClass
    static int myMethod()
    //Method work
    you dont need to have a instance of the class to call myMethod, you can do such things like this.
    int value = Myclass.myMethod();
    if myMethod isn't static you can't do this.. so, if
    class MyClass
    int myMethod()
    //Method work
    you CAN'T call
    int value = MyClass.myMethod();
    instead, you have to write
    MyClass m;
    m = new MyClass();
    value = m.myMethod();

  • A question about a method with generic bounded type parameter

    Hello everybody,
    Sorry, if I ask a question which seems basic, but
    I'm new to generic types. My problem is about a method
    with a bounded type parameter. Consider the following
    situation:
    abstract class A{     }
    class B extends A{     }
    abstract class C
         public abstract <T extends A>  T  someMethod();
    public class Test extends C
         public <T extends A>  T  someMethod()
              return new B();
    }What I want to do inside the method someMethod in the class Test, is to
    return an instance of the class B.
    Normally, I'm supposed to be able to do that, because an instance of
    B is also an instance of A (because B extends A).
    However I cannot compile this program, and here is the error message:
    Test.java:16: incompatible types
    found   : B
    required: T
                    return new B();
                           ^
    1 errorany idea?
    many thanks,

    Hello again,
    First of all, thank you very much for all the answers. After I posted the comment, I worked on the program
    and I understood that in fact, as spoon_ says the only returned value can be null.
    I'm agree that I asked you a very strange (and a bit stupid) question. Actually, during recent months,
    I have been working with cryptography API Core in Java. I understood that there are classes and
    interfaces for defining keys and key factories specification, such as KeySpec (interface) and
    KeyFactorySpi (abstract class). I wanted to have some experience with these classes in order to
    understand them better. So I created a class implementing the interface KeySpec, following by a
    corresponding Key subclass (with some XOR algorithm that I defined myself) and everything was
    compiled (JDK 1.6) and worked perfectly. Except that, when I wanted to implement a factory spi
    for my classes, I saw for the first time this strange method header:
    protected abstract <T extends KeySpec> T engineGetKeySpec
    (Key key, Class<T> keySpec) throws InvalidKeySpecExceptionThat's why yesterday, I gave you a similar example with the classes A, B, ...
    in order to not to open a complicated security discussion but just to explain the ambiguous
    part for me, that is, the use of T generic parameter.
    The abstract class KeyFactorySpi was defined by Sun Microsystem, in order to give to security
    providers, the possibility to implement cryptography services and algorithms according to a given
    RFC (or whatever technical document). The methods in this class are invoked inside the
    KeyFactory class (If you have installed the JDK sources provided by Sun, You can
    verify this, by looking the source code of the KeyFactory class.) So here the T parameter is a
    key specification, that is, a class that implements the interface KeySpec and this class is often
    defined by the provider and not Sun.
    stefan.schulz wrote:
    >
    If you define the method to return some bound T that extends A, you cannot
    return a B, because T would be declared externally at invocation time.
    The definition of T as is does not make sense at all.>
    He is absolutely right about that, but the problem is, as I said, here we are
    talking about the implementation and not the invocation. The implementation is done
    by the provider whereas the invocation is done by Sun in the class KeyFactory.
    So there are completely separated.
    Therefore I wonder, how a provider can finally impelment this method??
    Besides, dannyyates wrote
    >
    Find whoever wrote the signature and shoot them. Then rewrite their code.
    Actually, before you shoot them, ask them what they were trying to achieve that
    is different from my first suggestion!
    >
    As I said, I didn't choose this method header and I'm completely agree
    with your suggestion, the following method header will do the job very well
    protected abstract KeySpec engineGetKeySpec (Key key, KeySpec key_spec)
    throws InvalidKeySpecException and personally I don't see any interest in using a generic bounded parameter T
    in this method header definition.
    Once agin, thanks a lot for the answers.

  • Question about static context when using classes

    hey there.
    i'm pretty new to java an here's my problem:
    public class kreise {
         public static void main (String[] args) {
             //creating the circles
             create a = new create(1,4,3);
             create b = new create(7,2,5);
             System.out.println(a);
             System.out.println(b);
             //diameters...unimportant right now
             getDiameter a_ = new getDiameter(a.radius);
             getDiameter b_ = new getDiameter(b.radius);
             System.out.println(a_);
             System.out.println(b_);
             //moving the circles
             double x = 2;
             double y = 9;
             double z = 3;
             a = create.move();
             System.out.println(a);
    }creating a circle makes use of the class create which looks like this:
    public class create {
        public double k1;
        public double k2;
        public double radius;
        public create(double x,double y,double r) {
            k1 = x;
            k2 = y;
            radius = r;
        public create move() {
            k1 = 1;
            k2 = 1;
            radius = 3;
            return new create (k1,k2,radius);
        public String toString() {
        return "Koordinaten: "+k1+" / "+k2+". Radius: "+radius;
    }now that's all totally fine, but when i try to usw create.move to change the circles coordinates the compiler says that the non-static method move() can't be referenced from a static context. so far i've seen that my main() funktion MUST be static. when declaring the doubles k1, k2, and radius in create() static it works, but then of course when having created the second circle it overwrites the first one.
    i pretty much have the feeling this is very much a standard beginner problem, but searching for the topic never really brought up my problem exactly. thanks in advance!

    You can't access a non-static method from within a static context. So, you have to call move() from outside of the main method. main has to be static because, in short, at least one method has to be static because there haven't been any objects initialized when the program is started. There are more fundamental problems than with just the static context issue.
    I'm confused by your code though. You call create.move(), but this would only be possible if move() was static, and from what I see, it's not. Now that's just one part of it. My second issue is that the logic behind the move() method is very messy. You shouldn't return a newly instantiated object, instead it should just change the fields of the current object. Also as a general rule, instance fields should be private; you have them as public, and this would be problematic because anything can access it.
    Have you heard of getters and setters? That would be what I recommend.
    Now, also, when you are "moving" it, you are basically creating a new circle with completely differently properties; in light of this, I've renamed it change(). Here would be my version of your code:
    public class CircleTester {
        public static void main (String[] args)
             //Bad way to do it, but here's one way around it:
             new CircleTester().moveCircle();
        private void moveCircle()     //really a bad method, but for now, it'll do
            Circle a = new Circle(1,4,3);
            Circle b = new Circle(7,2,5);
            System.out.println(a);
            System.out.println(b);
            //diameters. Don't need to have a new getDiameter class
            double a_ = a.getRadius() * 2;     //Instead of doing * 2 each time, you could have a method that just returns the radius * 2
            double b_ = b.getRadius() * 2;
            System.out.println(a_);
            System.out.println(b_);
            //move the circle
            a.change(2,9,3);
            System.out.println(a);
    public class Circle {
        private double k1;
        private double k2;
        private double radius;
        public Circle(double x,double y,double r)
            k1 = x;
            k2 = y;
            radius = r;
        public void change(int x, int y, int r)
            k1 = x;
            k2 = y;
            radius = r;
        public String toString()
             return "Koordinaten: "+k1+" / "+k2+". Radius: "+radius;
        public double getRadius()
             return radius;
    }On another note, there is already a ellipse class: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/geom/Ellipse2D.html

  • About static method

    can static methods be overloaded
    can static methods do not have access tp implicit variable calles this

    No overloading concept for static members.
    Try this:
    public class testest extends test2 {
    public static void out() {
    System.out.println (" hello world from testtest ");
    public static void main(String s[]) {
    test2 x = new testest();
    x.out();
    class test2 {
    public static void out() {
    System.out.println (" hello world from test2 ");
    c:\>javac testest.java
    c:\>java testest
    It will give you: hello world from test2.
    The point is: static members are not attached to instance, but to class itself
    So if you do this:
    test2 x = null;
    x.out();
    1. do you think it will compile?
    YES
    2. so what is the result?
    Same, hello world from test2
    3. Why?
    Because you declare x as test2.
    What JVM do is, it will see what class is x, it will find out that x is class of "test2". Then it will execute: test2.out()
    rgds,
    Alex

  • Access Modifiers Effect on Static Method Hiding Question

    I am studying for my SCJP exam and have come across a question that I do not understand and have not yet found a satisfactory explanation.
    Given:
    package staticExtend;
    public class A{
         private String runNow(){
              return "High";
         static class B extends A{
              public String runNow(){
                   return "Low";
         public static void main(String args[]){
              A[] a=new B[]{new B(),new C()};
              for(A aa:a)
                   System.out.print(aa.runNow()+" ");
    class C extends A.B{
         public String runNow(){
              return "Out";
    }The output is "High High". The explanation in the sample exam from ExamLab was that because the runNow() method in A was private that only an explicit cast to the B class would invoke the runNow() method in B. I have verified that that is the case, but am not clear on how the runNow() method being declared static in B and how the private access modifier in A results in this behaviour.
    Any additional explanation would be greatly appreciated.
    Thanks in advance.
    -- Ryan

    Ryan_Chapin wrote:
    OK, so since runNow() in A is private the compiler determines that regardless of the available methods in any of it's sub classes that since we declared the original array reference as "A" that it will invoke the runNow() in A. It's also due to the fact that the invocation came from within A. You would have gotten a compile time error if you tried to place the code in the main method in another class.
    >
    My mistake about the second part that you mention. You are correct. runNow() in B is NOT static, but the class is static. I guess that was the red herring in this question I don't see how that is related. I actually think that the "red herring" was what I described above. The fact that the code was placed in A, and that private methods can't be overridden.
    and the fact that the class itself is static has nothing to do with the behaviour that is being illustrated. Is that correct?Correct

  • Question about static properties in implementation (.m) file

    I've been using some static properties in my implementation files so they can be accessed by class methods like so for example:
    #import etc
    static Class foo; // <-- Here is where I've been defining static properties
    @implementation Bar
    - init {
    foo = [Class new]; // initialize property
    + getObject { // now any where else in my code I can use [Foo getObject]
    return foo;
    - dealloc {
    [foo release];
    I've been doing this so that in other classes, I can simply go like:
    [Foo getObject]
    Can someone give me some more details about what's going on here though? It's been working but I'm nervous because I don't know much about it.
    ie. What kind of property is it? (nonatomic, retain)? Is this bad practice?
    Thanks to anyone who can shed some light on this.

    First off, it's not a property. It's a static variable. And the code you have isn't a good idea. Static variables should NOT be set via instance methods.
    Think about the following code:
    // In some other class
    Bar x = [[Bar alloc] init];
    Bar y = [[Bar alloc] init];
    Think about what just happened. In the 'foo' class you have now created two 'foo' objects and the first one is now leaked.
    The proper way to initialize static variables is with the 'initialize' class method. This is only ever called once, the first time the class is referenced.
    static Class foo;
    @implementation Bar
    + (void)initialize {
    foo = [[Bar alloc] init];
    - init {
    // Do nothing with 'foo'
    + (Bar)getObject {
    return foo;
    - (void)dealloc {
    // Do nothing with 'foo'
    The only downside, sort of, is that 'foo' is never dealloc'ed except when the app exits. But this isn't typically a problem.

  • Administration Panel Error and a Question about Static IPs

    Since there appears to be no other place to report errors within the latest generation of Linksys router firmwares, I thought the forums may be the best place.
    If you use remote access to your router's Administration management console, upon saving any changes you are sent to the
    "Your settings have been successfully saved." page. Upon clicking cancel it successfully attempts to route to the appropriate hostname but does not consider the port being used; therefore, unless you have your management console hosted on port 80 it does not bring you back to the right place.
    This is mostly an annoyance.
    My question is I'm wondering if it's possible to assign static IP addresses from the router.
    On my older (much older) Linksys routers (before Cisco bought them out) you could easily assign static IPs.
    I cannot seem to find a way to do with newer generations.  All suggestions recommend assigning static IPs from the
    network devices themselves, however that poses problems on modern mobile devices which don't let you do that,
    and for laptops that are brought into a lot of different networks it becomes an annoyance to change those settings manually.
    I have a EA4500 router.
    Solved!
    Go to Solution.

    You want to assign a specific ip address to your computers/network devices thru the router? You can use the DHCP reservation feature of this router.
    "A DHCP Reservation is a permanent IP address assignment.  It is a specific IP address within a DHCP scope that is permanently reserved for leased use to a specific DHCP client."
    Please check this link:
    http://www6.nohold.net/Cisco2/ukp.aspx?vw=1&docid=71dac52653fa4944ae5e4f94ebdf9586_17362.xml&pid=80&...

  • See this question about static object

    1)static A a =new A();
    2) A a1=new A();
    what is the difference between them?

    static A a =new A();
    When this line is written in another class say : class b;
    a is accessible without the need for declaring an object of b.
    i.e., b.a
    Not in the other case.
    Many factory classes and methods are accessed this way coz, the classes are private and abstract, so u cannot make an object of that class.
    For example:
    System.out.println() - here println() is a method, out is an object of some class that is declared static in the class System. if it were'nt static, then we had to make an object of the System class and then access the out object,
    hope this helps
    let me know

  • Newbie question about abstract methods

    hey, I'm working on a web application that I was given and I'm a little confused about
    some of the code in some of the classes. These are some methods in this abstract class. I don't understand
    how this post method works if the method it's calling is declared abstract. Could someone please tell me how this works?
        public final Representation post(Representation entity, Variant variant) throws ResourceException {
            prePostAuthorization(entity);
            if (!authorizeGet()) {
                return doUnauthenticatedGet(variant);
            } else {
                return doAuthenticatedPost(entity, variant);
    protected abstract boolean authorizeGet();Thanks
    Edited by: saru88 on Aug 10, 2010 8:09 PM

    Abstract Methods specify the requirements, but to Implement the functionality later.
    So with abstract methods or classes it is possible to seperate the design from the implementation in a software project.
    Abstract methods are always used together with extended classes, so I am pretty sure that you are using another class.
    Btw: Please post the Code Keyword in these brackets:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

  • Question about static ip

    Here's the situation:
    I live in a house of about 30  tenants. The place uses a cisco WRVS4400N router. It seems that my  computer gets assigned a temporary ip automatically and then there will  be times when I get "kicked out" and my computer doesn't get connected  to the internet. Sometimes for few minutes and sometimes for hours.
    No  idea what happens there but could be that there are no ips left to  assign to my computer and someone else gets the ip address.
    Anyway I'm trying to find out if I can configure my computer with a static ip.
    The  maximum number of dhcp users was changed from 50 to 100 by me. IDK if  that means that I can assign a static ip from 1 to 100 but say I pick a  number 160 so the ip would be xxx.xxx.x.160.
    1. What are the steps I have to undertake to configure my computer on the router page? What info. do I have to modify?
    2. After I modify settings on the router page, do I have to change settings on my computer?

    Al,
    You do not need to change anything in the router. You can simply assign your PC a static IP address. If your DHCP pool is xxx.xxx.x.100-200, use something like xxx.xxx.x.99 on your PC to avoid IP conflict. (assign an address that is not used by the DHCP server) If your router is xxx.xxx.x.1, set that as the Default Gateway and Primary DNS Server on the PC. You can also use 8.8.8.8 as the DNS Server if you wish. The Subnet Mask should be 255.255.255.0
    See the following link for excellent instructions about giving a PC a static IP:
    http://www.howtogeek.com/howto/19249/how-to-assign-a-static-ip-address-in-xp-vista-or-windows-7/

  • Basic Cryptography Question about Cryptograpic Methodes

    Hi
    I have some text data that i need to encrypt and save to a file (kind of a licence file). Than that file is distributed with the software. Upon runtime the software should be able to read in that crypted data file and decrypt it so it can read the information for use.
    I know how this is done using DES for example. But with DES i have to distribute the DES Key with the software, so everbody could use that key to create new encrypted data files.
    What i'm looking for is something like a key i can use to encrypt the data and another key that can only be used to decrypt the data but not for encrypting it, so i can destribute that key with the software with out the danger that anybody can use that key to create new data (licence) files.
    Is there a cryptography mehtode to do this? If yes, is that methode available in JCE?
    I'm a newbie to crypthography, i just read little about the basic concepts, so i'm very thankful about your help.

    I'm not sure whether i understand what you mean. I don't see a reason why i have to exchange any kind of data with the client.
    i thought i package the public key and the encrypted data file with the software i distribute. Than, upon runtime the software loads the public key (as a serialized object) and the encrypted data file and decryptes the data file.
    But this just fits my needs, if the public key may just be used to decrypt the crypted data file and not for encryption. I'm a little bit confused about this point, because i read a lot in the past hours about this topic and the statement was, that private keys are used to decrypt and public keys are used to encrypt. So what i need is the opposite. And i couldn't find such an algorithm until know.
    Maybe you can help me to see that a little bit clearer?
    Thanks a lot for your help!

  • Question about functions methods and variables

    Sorry but i couldn't figure out a better title.
    When does a method alter the variables it gets directly and when does a method just alter a clone of the variables it gets?
    How about a funcion?
    for example:
    public void (int i)
    i = 4;
    sometimes this method alters the integer which was given to it directly and sometimes it automatically creates a clone of the integer and alters that one. I just can't figure out why a method would do the first or the second.
    Im trying to achieve the direct changeing of the given variable without creating an unessecary clone.
    Thank You

    Comp-Freak wrote:
    Sorry but i couldn't figure out a better title.
    When does a method alter the variables it gets directly and when does a method just alter a clone of the variables it gets?
    How about a funcion?
    for example:
    public void (int i)
    i = 4;
    sometimes this method alters the integer which was given to it directly and sometimes it automatically creates a clone of the integer and alters that one. I just can't figure out why a method would do the first or the second.
    Im trying to achieve the direct changeing of the given variable without creating an unessecary clone.
    Thank YouThats quite all right about the title, trust me we get much worse titles on this forum. Most of the time to the effect of "Plz urgentlly!!!!111one"
    In Java, all variables passed into methods are passed by value, which means that if I pass an int variable to a method, that methods argument will always be a seperate variable. There is no way to pass variables by reference so that you are altering the original variable you passed in.
    It actually works the same way for reference variables that point to a particular object.
    public Object o = new Object();
    methodOne(o);
    public void methodOne(Object oArg) {
      o == oArg;  //true
    }It is essentially the same in this case, there are two seperate reference variables here, o and oArg is created once the method is called. There is only one Object created however and both reference variables point to it, so an == check will verify this that it is true.

  • Question about static (+multithreading)

    Sample program for multithreading:
    cvidir\samples\utility\Threading\ThreadSafeVar\IncrementValue.prj
    Why all of global variables and functions are static ?
    regards
    Frog

    This is a CVI question and should be posted to the LabWindows/CVI forum instead. Static flags are used to tell the compiler that these global declarations are not used outside this code module (C file). It's good programming practice to declare global variables only used in one module as static.
    Best Regards,
    Chris Matthews
    National Instruments

  • Question about static

    A class variable is any field declared with the static modifier; this tells the
    compiler that there is exactly one copy of this variable in existence,
    regardless of how many times the class has been instantiated.
    So I thought , I could have an builtin-counter with this code-snippet
    public class SpieleInfo {
        // ....public int creator = 0;    
        private static int spielNummer = 0;     // aktuelle Nummer
        public SpieleInfo(int clientId) {
            super();
            spielNummer ++;
        public static int getSpielNummer() {
            return spielNummer;
        }But for each   SpielInfo spielInfo = new SpielInfo (anInt ) ;
      System.out.println(spielInfo.getSpielNummer() )I always get a zero for output.
    I dont see my mistake
    TIA
    Hanns

    public class SpieleInfo {
         //      ....public int creator = 0;    
        private static int spielNummer = 0;     // aktuelle Nummer
        public SpieleInfo(int clientId) {
            super();
            spielNummer ++;
        public static int getSpielNummer() {
            return spielNummer;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SpieleInfo spielInfo = new SpieleInfo (4 ) ;
              SpieleInfo spielInfo2 = new SpieleInfo (4 ) ;
                System.out.println(spielInfo.getSpielNummer() );
    }Tried your code it works for me sorry, the only change i had to make was to add the e into SpieleInfo variable declaration you dont have another class called SpielInfo do you?
    Message was edited by:
    mmi1

Maybe you are looking for

  • Music will not add to iTunes (MP3 Format)

    I'll try to make this quick. About a month ago my hard drive was over flooded with MP3's. I decided to get an external 250GB Hard drive. I moved all of my files over to the external hard drive. iTunes "lost" the connection to those files. Rather than

  • Vertical text with JTextPane?

    I am writing an application for displaying and editing sign language texts using Sutton SignWriting. It is a sign language writing system which enables the Deaf people to write to each other in their own language. And it is language-neutral, that mea

  • EWA for non-abap not triggering with SDCCN session

    Hi I can manually download the session and generate EWA for java stack but its not automatically generated with SDCCN report. Its a double stack system, i am getting EWA for abap stack but not for java stack. Guide on note 976054 do not clearly menti

  • How many fields can be added in va01

    Hello All, I'm trying to add new fields in the additional data B tab of the header but I noted that I can't add as much fields as I want even if in the dynpro 83909/SAPMV45A still have space. Is there any limitiation of number of fields to be added?

  • Windows installati​on disc

    hi there i hve a hp g61 but by accident i have deleyed my files so rang the help line and purchased the hp recovery dics but when i put these into my laptop nothing happens i can i get this to work help This question was solved. View Solution.