What a static method cannot be overriden?

Parent class
public class Person {
   private String surname;
   private String firstName;
   private String secondName;
   public Person(String surname,
                 String firstName,
                 String secondName) {
        this.surname = surname;
        this.firstName = firstName;
        this.secondName = secondName;
   public static void test() { ; }
}Sub class
public class Member extends Person {
     private int membershipNumber;
                 public Member(String surname,
                  String firstName,
                  String secondName,
                  int membershipNumber) {
          super(surname, firstName, secondName);
          this.membershipNumber = membershipNumber;
     public String toString() {
          return membershipNumber + "-" + super.toString();
     public void test() { System.out.println("test") ; }
}And I got compilation error :
H:\java\wshp2>javac *.java
Member.java:20: test() in Member cannot override test() in Person; overridden me
thod is static
public void test() { System.out.println("test") ; }
^
1 error
H:\java\wshp2>pause
Since static method and the overriding method are going to be used differently (in different ways), why it can't be allowed?
Static method is a Class method whereas the overriding method is a instance method, they can be distinguished. What is the reason behind this?
Please enlighten me.
Thanks

Are final method bound at compile-time?Basically when a method is "bound" cannot be used to explain the behaviour of methods in Java. It's the other way around. It's the characteristics of a method that decides when it can be "bound". But that's an implementation issue and not part of the language itself.
A static method cannot be overriden because it's not meant to be overridden. It's against the semantics of a static method to be overridden. Also if you declare a method final you decide that you don't want it to be overriden. In both cases, based on this non-overriding restriction, the compiler can decide when to "bind" the method.

Similar Messages

  • Static method are not overriden ?

    Hi,
    as I try to understand java in depth, I come back with this simple question:
    public class hiddenVar1 {
    boolean aVariable=true;
    public static void main (String [] args) {
    System.out.println("Hello");
    public class hiddenVar2 extends hiddenVar1 {
    boolean aVariable;
    public hiddenVar2() {
    aMethod();
    void aMethod() {
    aVariable = false;
    System.out.println(aVariable);
    System.out.println(super.aVariable);
    public static void main (String [] args) {
    new hiddenVar2();
    hiddenVar1.main(new String[2]);
    The result is :
    false
    true
    Hello
    Conclusion:
    the main static method of hiddenVar1 as not been overrided by the main static method in hiddenVar2.
    So inheritance does not apply for static method ?
    Any explanation ?
    Thank's.
    John

    Firstly i think there should not be two public classes in only one file it gives compile time error.
    Secondly the output is correct.
    Static methods cannot be overriden because it will get initialize when u create instance of the class so u r calling
    -- new hiddenVar2();
    so it calls the constructor in that respective method is called.
    And the second line is calling the super class so it calls the main method of that class and prints "hello"
    hiddenVar1.main(new String[2]);

  • This static method cannot hide the instance method from...

    What means the error message "This static method cannot hide the instance method from Referee"?
    Referee.java is a interface. I implemented it in the class RefereeMyName.java and made a method in that class to be static. Thats why I received that error message.
    But can't I use static methods when I have implemented a interface in that class? I want to have a Player.java class which I want to access RefereeMyName.getTarget(). I cannot use a instance instead because I wouldn't receive a valid return value then (RefereeMyName is the client class).
    What is the solution?

    Hi,
    Well i do not think that you can do that b'cos that way you are not giving the same signature for the method as that exists in the interface. I do not know how other way it can be done but if something urgent for you then you can remove that method from that interface and only define in the class.
    Regards,
    Shishank

  • Non static method cannot be referenced from a non static context

    Dear all
    I am getting the above error message in my program.
    public void testing(Vector XY){
    RecStore.checkUnits(XY);
    }method checkUnits is non static and cannont be called from a non static context. I don't see the word static anywhere...
    I have done a wider search throughout the main class and I'm haven't got any static their either.
    Any ideas?
    Thanks
    Dan

    Yup
    I had pared down my code, infact it is being called from within a large if statement.Irrelevant.
    But the same thing still holds that there is no static keyword used.Read my previous post. Calling checkUnits using the class name:
    RecStore.checkUnits(XY);implies a static context--in order for that call to work, checkUnits must be static. That's what your error message is saying--you are trying to call the non-static method "checkUnits" from the static context of using the class name "RecStore."

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    ~

  • What is static method

    I can not understand how to use static method
    What is the difference between
    int a;
    static int a;
    what is the meaning of static??

    I would add that a static member exists for the class independently of any instances of the class.
    This means that you can refer to it at any time by using TheClass.theMember.
    This applies to the methods too, like TheClass.theMethod().

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Static methods, what for?

    What are static methods for? is there something that is not possible through methods associated with instances (non-static methods) ?

    There are many examples of static mehods in the Java API. For example the Math or the System class. All methods in this classes are static. So you dont have to instantiate the system class. In fact it is even not possible to instantiate the System class. System is final and all Constructors are private.
    Another use for static methods is the access to private static variables.

  • Static methods in interfaces

    Java cognoscenti,
    Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a difference

    No, it's not the same. You are not "defering the
    implementation of a static method" because static
    methods are never polymorphic.
    Static methods cannot be abstract for this reason, and
    only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
    A short summary of what I've learnt so far:
    - interfaces cannot contain static methods
    - abstract classes cannot contain abstract static methods
    - static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
    /* output
    SuperClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    SuperClass.someMethod()
    SubClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    public class Test {
      public final static void main(String[] args) {
          // output: SuperClass.someMethod()
          new SuperClass().someMethod();
          // output: SubClass.someMethod()
          new SubClass().someMethod();
          // output: 2x SuperClass.someMethod()
          SuperClass someClass1 = new SubClass();
          someClass1.someMethod();
          showSuper(someClass1);
          // output: 2x SubClass.someMethod()
          SubClass someClass2 = new SubClass();
          someClass2.someMethod();
          showSub(someClass2);
          showSuper(someClass2); // SuperClass.someMethod()
      public final static void showSuper(SuperClass c) {
            c.someMethod();
      public final static void showSub(SubClass c) {
            c.someMethod();
    class SuperClass {
      public static void someMethod() {
        System.out.println("SuperClass.someMethod()");
    class SubClass extends SuperClass {
      public static void someMethod() {
        System.out.println("SubClass.someMethod()");

  • Static Methods, the case of HashMap

        static int hash(Object x) {
            int h = x.hashCode();
            h += ~(h << 9);
            h ^=  (h >>> 14);
            h +=  (h << 4);
            h ^=  (h >>> 10);
            return h;I was cruising the HashMap class. And I noticed right away that all non interface methods were static package methods. Now isn't that bad OOP practice? Right. It breaks the inheritance relationship.
    It means I cannot make a subclass of HashMap and re-write that hash function. Was that intentional?
    on a OOP perspective or
    on a down to earth matter,
    Are static method more performant in speed? Or memory ( i guess yes here)? or what?

    I was cruising the HashMap class. And I noticed right
    away that all non interface methods were static
    package methods. Now isn't that bad OOP practice?
    Right. It breaks the inheritance relationship.
    It means I cannot make a subclass of HashMap and
    re-write that hash function. Was that intentional?If they are package-private, I take it for granted they didn't want application developers to redefine these methods.
    If they are static, they are also preventing themselves (Javasoft) to override them in subclasses that would be included in the JDK.
    I'd say in both cases, that it is intentional, since, at least in the case of the hash function, the intent is to disperse hash results even for low-dispersing custom hash functions, as was explained in another thread in ALT (wasn't it you already? ;-).
    This is maybe questionable, but defendable, that they didn't want any subclass to mess with these "optimizations".
    You can regard this as poor OO practice, but this is no more hampering you that if they had declared the method as private.
    I acknowledge that declaring the method private has the advantage of making explicit that they don't want anyone to override it.
    But by declaring it static package, they ensure no-one can override it, so the other methods in HashMap relying on this method are guaranteed that no subclass can mess with it, but other classes in the same package (say, WeakHashMap, HashSet,...), can call it. all the same
    Are static method more performant in speed? Or memory
    ( i guess yes here)? or what?Static methods are not faster in themselves, but invoking them may be, since they can be "statically" resolved.
    When the calling class is loaded in memory, the callee is loaded too, and the interpreter or JIT or HotSpot is free to inline the static method's body (no indirection).
    Even if it doesn't, invoking the static method implies to moving the program counter or pointer, or whatever, to an adress that has already been resolved once and for all (one indirection),
    whereas invoking a virtual method implies a double indirection, looking up the address in some kind of dynamic table (one per class, determined by the target object's leaf class).
    There are indeed two different bytecodes for these two situations!

  • On static method override-

    just posted an example of over riding a static method . Is this legal? I mock cert exam is saying that static methods can not be overridden, What's the truth?

    As I know static method cannot override by non-static method and vice versa.

  • Redefine static method?

    It seems that I cannot redefine a static method in a subclass in ABAP OO, right?
    Is there a reason for that? Is this like this in other languages as well?

    That's true. You cannot redefine static methods in ABAP OO.
    I can add that a class that defines a public or protected static attribute shares this
    attribute with all its subclasses.
    Overriding static methods is possible for example in Java.
    This simple piece of code illustrates this:
    public class Super {
        public static String getNum(){
            return "I'm super";
         public static void main(String[] args) {
             System.out.println("Super: " + Super.getNum());
             System.out.println("Sub: " + Sub.getNum());
    public class Sub extends Super{
        public static String getNum(){
            return "I'm not";
    The output is:
    Super: I'm super
    Sub: I'm not
    When overriding methods in Java you must remember that an instance method cannot override a static method, and a static method cannot hide an instance method.
    In C# a static member can't be marked as 'override', 'virtual' or 'abstract'. But it it is possible to hide a base class static method in a sub-class by using the keyword 'new':
    public class Super
      public static void myMethod()
    public class Sub: Super
      public new static void myMethod()

  • Can Static Methods be overridden ?

    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj This is one small program code which i wrote ,which did not allow static methods to be overridden,but no error as such was displayed.
    package fundamentals;
    class SuperClass
      public static String getName()
           return "HI,CLASS...SUPER CLASS";
      public int getAge()
           return 20;
    } // END OF SUPER CLASS
    public class SubClass extends SuperClass{
    public static void main(String[] args)
              SubClass objSubClass=new SubClass();
              SuperClass objSuperClass=new SubClass();
              System.out.println(objSubClass.getName());      // SUB CLASS
              System.out.println(objSuperClass.getName());   // SUPER CLASS
              System.out.println(objSubClass.getAge());        // SUB CLASS
              System.out.println(objSuperClass.getAge());     // SUPER CLASS
                     public    static String getName()
                       return "HI,CLASS...SUB CLASS";
                     public int getAge()
                        return 40;
    } // END OF MAIN CLASSWhich gives the O/P :
    HI,CLASS...SUB CLASS
    HI,CLASS...SUPER CLASS
    40
    40So,the static method was not overridden.
    But ,why was no error message displayed ?
    Also when i modify the subclass static method,by removing the static keyword as follows :
    public  String getName()
                       return "HI,CLASS...SUB CLASS";
                     }A Error Message as :
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         This instance method cannot override the static method from SuperClassis displayed.
    Why this message is displayed after i remove the static keyword ?
    So can we say that Java does not allow static method to be overridden but does not display a compile/run time error when this is done ?
    Is this a bug as stated by kajbj ?
    Please let me know if i am not clear.If this question has been answered somewhere else in this forum,kindly let me know.
    Thank you for your consideration.

    amtidumpti wrote:
    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj
    Sigh! Amti, are you being misleading on purpose? Kaj did not "post a program which did allow overriding of static methods." He posted a program which used the annotation @Override on a static method, like this:
    class A {
        public static void m() {}
    class B extends A {
        @Override public static void m() {}
    }He wondered why it didn't generate an error message. Well, it does now:
    A.java:6: method does not override or implement a method from a supertype
        @Override public static void m() {}
        ^
    1 error

  • Interfaces and static methods

    Hi All,
    Does anyone know why you can't declare static methods in an interface? Is there a way round this problem?
    Cheers...

    But this won't:public class StijnsClass
      public static void aMethod()
        System.out.println("StijnsClass.aMethod()");
      public static void main(String[] arg)
        StijnsClass stijnsInstance = new StijnsSubClass();
        stijnsInstance.aMethod();
        System.out.println("Nothing else to say, here?");
    class StijnsSubClass extends StijnsClass
      public static void aMethod()
        System.out.println("StijnsSubClass.aMethod()");
        super.aMethod(); // Wrong!!!
    }You will get:
    "StijnsClass.java:21: non-static variable super cannot be referenced from a static context".
    If you remove static from the subclass method definition, you will get:
    "StijnsClass.java:18: aMethod() in StijnsSubClass cannot override aMethod() in StijnsClass; overridden method is static"
    That's the point. You aren't extending the method; you are only hiding it. To make it work, both methods must be instance methods, ergo, static methods cannot be extended.

  • About overriding static method inheritance

    I have some class PO2VOPropertyUtilsBean which extends the org.apache.commons.beanutils.PropertyUtilsBean.
    In PropertyUtilsBean,there is a method:
    protected PropertyUtilsBean getInstance() {}I override it in my extend calss PO2VOPropertyUtilsBean:
    protected PO2VOPropertyUtilsBean getInstance() {
          return new PO2VOPropertyUtilsBean();
    }I use Eclipse3.1+Myeclipse4.0,when i choose java5.0 as complier,that all be ok.
    But when i copy the source to my company, my pc uses java1.4 as compiler,it show me errors in the getInstance() method:
    imcompartible return type,it should return PropertyUtilsBean.
    Why?

    Ok, so the getInstance() methods are indeed static.
    As Kaj said, static methods cannot be overridden.
    You would call the method by the classname. For example:
    PropertyUtilsBean bean = PropertyUtilsBean.getInstance();If you write a class PO2VOPropertyUtilsBean with a getInstance() method, the call above will still go to class PropertyUtilsBean, and not to your derived class. After all, how is Java supposed to know that you want to have the method in PO2VOPropertyUtilsBean called? You would need to change the call:
    PropertyUtilsBean bean = PO2VOPropertyUtilsBean.getInstance();

Maybe you are looking for

  • Can anybody tell me how to change the icon pic in iphone 3g 4.2.1

    I have seen many peple having a non jailbroken iphone with different app pucs. Tell me how to do it. I am using iphone 3g ios 4.2.1 non jailbroken and itunes 10.5 windows.

  • Render Dynamic PL/SQL region as PDF?

    Hi! I would like to be able to render a Dynamic PL/SQL region as a PDF. Anybody have an idea how to do this or even if it can be done? This is not a report region. Also any idea's on how I might do pagination in a dynamic PL/SQL region? Any hope that

  • Problem installing XI 2.0

    I am at the last step of the installation process, running the XI SAPInst.  I am running into an error on the screen that asks for the SAP J2EE Administrator account.  I enter my information then receive the following error. "The J2EE Engine has patc

  • Acn a Mac get a virus or malware?

    I inadvertently opened MacKeeper and finally removed it but now I have a malware on my Mac which causes it to go to a search engine that is not right. I can't remove it when I open a browser home page. Any ideas?

  • How do we do the equivalent of "restore in place" please?

    How do we do the equivalent of "restore in place" please?