OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

Dear Experts ,
I had searched the SDN , but unable to find out the satisfactorily answers ..
Can anybody let me know the reason for the following Confusion in Oops Concept
Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
Question 2 : Why can't Static Method be Abstract ?
Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
Thanks in Advance
Saurabh Goel

As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
Hope it clarifies!!!
Thanks,
Vishesh

Similar Messages

  • Why the method can be called in this way?

    Hi all,
    The following is JAVA SWING TREE custom data models program. There are two files in the program: one is TestFrame.java, and the other is MyDataModel.java. I only posted the important part on the Forum.My question is how method getChild(...) in MyDataModel.java was called in the program? Why I couldn't see the statement like tree.getChild(..) in TestFrame.java? After adding PRINT statements, I know the method getChild(..) was called automatically when object tree was initialized , but I don't know why. Thank you in advance.
    ======
    TestFrame.java
    // Imports
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    class TestFrame extends JFrame
    // Instance attributes used in this example
    private JPanel topPanel;
    private JTree tree;
    private JScrollPane scrollPane;
    // Constructor of main frame
    public TestFrame()
    // Create a new tree control
    MyDataModel treeModel = new MyDataModel( root );
    tree = new JTree(treeModel);
    =========
    ==========
    MyDataModel.java
    import javax.swing.tree.*;
    class MyDataModel extends DefaultTreeModel
    private DefaultMutableTreeNode root;
    private String rootName = "";
    public MyDataModel( TreeNode root )
    super( root );
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)root;
    rootName = (String)parentNode.getUserObject();
    System.out.println("rootName is: "+rootName);
    public Object getChild( Object parent, int index )
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)parent;
    String parentName = (String)parentNode.getUserObject();
    System.out.println("parentName is: "+parentName);
    if( parentName.equals( rootName ) )
    return super.getChild( parent, index );
    else
    return new DefaultMutableTreeNode( cardArray[index] );
    }

    This is the first time I saw this usage. I understood it now, but I was afraid I missed some important concepts on "interface as parameter in the constructor". Therefore, I am wondering where I can find some online document about it in order to understand the usage clearly.
    For example, if there are a few method implementations of interface TreeModel in MyDataModel.java, which methods will it call after calling JTree constructor? all methods or only part of them?
    Thanks

  • Why a method can not be invoked in JSP ???

    I define a method in a JAVA Class file,as this:
    public Enumeration getElementsNamed(String name, String parentname) {
    Element elem = doc.getDocumentElement();
    NodeList nodes = elem.getElementsByTagName(name);
    int size = nodes.getLength();
    Vector elemVec = new Vector(size);
    for (int i = 0; i < size; i++) {
    Node node = nodes.item(i);
         if (nodes     .item(i).getParentNode().getLocalName().equals(parentname)) {
              elemVec.addElement(new UddiObject((Element) node));
              return elemVec.elements();
    I want to get a Element who's Localname is the name and his parent Element's laocalname is the parentname from a DOM tree.
    This can be run well in a normal Java environment just as JDK1.4.
    and is a JSP file,I import the Class first.
    and invkoed the method in somewhere, the TOMCAT give me an error:
    The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException     
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
    the JSP file is :
    <%@ page import="java.util.*,org.w3c.dom.*, edu.hunnu.uddi.*, java.sql.*,java.io.*,edu.hunnu.uddiserver.util.*,edu.hunnu.uddiserver.inquiry.*" %>
    <h1>Get tModel</h1>
    <%
         Connection con = SqlConnection.getConnection();
    String Description="";
         String detail ="<get_tModelDetail generic=\"2.0\" xmlns=\"urn:uddi-org:api_v2\"><tModelKey>"+tModelKey+"</tModelKey></get_tModelDetail>";
         ByteArrayInputStream bas = new ByteArrayInputStream(detail.getBytes());
         TModelDetails tmodelDetails = new TModelDetails( new Get_TModelDetail(bas), con);
    UddiObject obj=tmodelDetails.getData();
         obj=obj.getElement(UddiTags.TMODEL);
         Description=Description+((TModel)obj).getDescription();
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
              Error at this
              %>
    <%%>
    WHY??? and HOW????

    oh~It is my mistake.
    and the JSP file would be:
    <%@ page import="java.util.*,org.w3c.dom.*, edu.hunnu.uddi.*, java.sql.*,java.io.*,edu.hunnu.uddiserver.util.*,edu.hunnu.uddiserver.inquiry.*" %>
    <h1>Get tModel</h1>
    <%
         Connection con = SqlConnection.getConnection();
    String Description="";
         String detail ="<get_tModelDetail generic=\"2.0\" xmlns=\"urn:uddi-org:api_v2\"><tModelKey>"+tModelKey+"</tModelKey></get_tModelDetail>";
         ByteArrayInputStream bas = new ByteArrayInputStream(detail.getBytes());
         TModelDetails tmodelDetails = new TModelDetails( new Get_TModelDetail(bas), con);
    UddiObject obj=tmodelDetails.getData();
         obj=obj.getElement(UddiTags.TMODEL);
         Enumeration enum=obj.getElementsNamed("description","tModel");
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
              Error at this
              %>
    and the variable "obj" :
    <tModel operator="www.hunnu.edu.cn"tModelKey="uuid:50C693A0-7AB8-11D5-93A0-CFE2D4CCB519"><name>simple.services</name><description>This is a basic tModel for service providers and consultant</description><overviewDoc><overviewURL>http://www.hunnu.edu.cn</overviewURL><description>Service documentation can be obtainedfrom the URL provided</description></overviewDoc><identifierBag/><categoryBag/></tModel>

  • Why my method can not receive the string from JNI

    JNIEXPORT jstring JNICALL Java_playaudio_BeatTrack_myBeatTrack
    (JNIEnv *env, jobject obj, jstring wavfile)
    const char* filename = env->GetStringUTFChars(wavfile,0);
    BeatTrack(filename);
    env->ReleaseStringUTFChars(wavfile,filename);
    return NULL;
    }for my BeatTrack method, I just need the filename, then it can run, if I comment the BeatTrack(filename);, then no problem, for the java calling, of course, my BeatTrack(const *char filename) has no problem, cause I have test it,,
    but I call this method in java, the error is as follows,
    Java VM: Java HotSpot(TM) Client VM (10.0-b19 mixed mode, sharing windows-x86) # Problematic frame: # C [beattrack.dll+0x130b] # # An error report file with more information is saved as: # D:\programs\playAudio\hs_err_pid11684.log # # If you would like to submit a bug report, please visit: # http://java.sun.com/webapps/bugreport/crash.jsp # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. any idea??

    1) What class is "missing?"
    2) Where is it?

  • Static methods inside class in jsp can't make it work

    Hello all i can't understand it why i can't declare the method as static method ?
    public class Request{
              Request(){}
              private String paramValue;
              public static String getRequestParam(HttpServletRequest request, String paramName, String defaultValue){
                   paramValue = request.getParameter(paramName);
                   return paramValue != null ? paramValue : defaultValue;
    im geting this error :
    The method getRequestParam cannot be declared static; static methods can only be declared in a static or top level type
    can't i do inner class ?
    or other sulotion for me not to make instences of class's but to use the class static methods?

    Hi, try this:
    public class Request{
              Request(){}
              private static  String paramValue;
              public static String getRequestParam(HttpServletRequest request, String paramName, String defaultValue){
                   paramValue = request.getParameter(paramName);
                   return paramValue != null ? paramValue : defaultValue;
          }it should work. the problem in you code is that you are trying to referance an non-static object with a static one!
    Message was edited by:
    Adelx

  • Can static methods overridden

    help me to know that static methods can be overridden with example

    No u can not override static,private or final methodsIt would be interesting for the OP to know why (the reason is very different in each of the three cases).
    @OP: the same question was posted a fey days ago and I posted there a reply, if you do a search in the forum you'll find it.

  • 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.

  • What's wrong with static methods?

    Answers on an postcard please.

    I think the point here is that sometimes people come from a procedural background (or maybe no background) and they start with main, and one static method leads to another. They reach a tipping point where they are reluctant to define non-static methods to a class because it's all static elsewhere. And static method can't access instance data, so their data becomes largely static as well. When the dust settles, they are programming procedually in Java. So too many static methods is a sign that you may be programming procedurally instead of doing OOP, but using static appropriately is still cool.
    And let's not get pedantic. What goes wrong if I make my String class's getLength method static?
    public final class MyString {
        private int length;
        public static int getLength(String s) {
            return s.length;
    }It's a misuse of static, but it doesn't break my design.

  • Non-static method/object cannot be referenced from a static context...?????

    What does this mean. I know about static, but I don't understand why I get this so many times.
    I try to do something pretty normal and this is what I get a lot of times. I mean: the main() method should be static right? Then what good is the main() method if you cannot let it do stuff for you like this:
    public class Test extends JFrame
        public Test
            setSize( 100, 100 );
            show();
    public static main( String args[] )
        Test window = new Test();
        draw();
    public void draw()
        blablabla whatever I want to do, a lot of times I can't.....
    }Why is this, what is the reason for Java to forbid this and what can I do about it?

    Your draw() method, since it isn't defined as static is considered by Java to be part of your Test object; hence, it can only be invoked in the context of an existing instance of your object. In other words, any Java program that wanted to use your draw() method would have to create an instance of your Test class using something likemyTest = new Test()Your main method, however, is something different. Since you want to execute your class as a program, the Java run-time environment needs to have standard starting point. This starting point is the main method. The problem is that the main method must be static, because the run-time environment cannot be expected to know beforehand the correct way to create an instance of your class so that non-static methods can be invoked. The drawback is that your main method can only directly access methods that are defined as static.
    There are two possible solutions to this problem, and which of the two you want to use depends on the object-oriented nature of your program.
    On the one hand, if your draw() method is closely tied to the object itself, if the draw() method is actually drawing your object or a part of it, it should be left as an instance method, and you should simpy use the instance of the object you created in your main method:public static main( String args[] )
        Test window = new Test();
        // maybe some code to generate something to draw???
        window.draw();
    }This is what I think you are trying to do.
    On the other hand, if your draw() method was some kind of universal method that didn't depend in any way on the current configuration of your instance, you could simply define draw() as static at which point your main method (or a method in an external class) could invoke it directly, without a corresponding instance. But if you did that, the draw() method itself would only be able to access static variables and methods.
    Doug

  • 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 in interface (Yes, once again!)

    I know there has been many questions about why static methods in interfaces are not allowed. I know it is forbidden by the JLS. But does anyone know the exact reason for this? Is it just a design issue or are there technical difficulties with allowing it?
    I can't think of any reason that it should be impossible to allow static methods in interfaces. I don't even think it would be very difficult to do. More importantly, it could probably be done without breaking existing code and existing JVMs (not too sure about the last one).
    So once again: Was the choice of not allowing static methods in interfaces a design choice or a technical choice?

    A better example of what you are suggesting is surely ...
    interface i {
        static void one();
    class a implements i {
        static void one() {
            // do something
    class b implements i {
        static void one() {
            // do something else
    }What would be the point of ever doing this?
    You cant call i.one() as the method doesn't exist without an instance of an implementing class.
    To actually ever be able to use that method you would effectively be casting an INSTANCE of a or b -> i. If you have an instance of an a or b then there is absolutely no reason for that method to be static.
    If you wanted to implement some sort of class (ie static) behaviour then class a could call its own internal static method from within the 'one' method.
    To get right to the point ... there isn't one. If it gets added to the language (and I can't see it in my wildest dreams) then Sun have lost their marbles, surely?
    Unless someone can give a good example of when it might be correct and useful to do so? I can't even see how it would be a convenience as it is completely unusable, no?

  • No static methods for Interfaces ?

    Hi,
    I was going though some documentation about the interfaces and it says that, an interface methods must not be static.
    Can someone please explain or direct me in the direction which tell me why the internet methods cannot be static.
    Thanx.
    Mel

    Defining a static method in a interface would be useless, since static methods can't be executed with dynamic binding. You'd have to know the name of the implementing class of the interface at compile time to call it, which would negate the need for an interface.
    For more details google it, that question has been asked thousands of times.

  • Class constructor is actually "static" method, as Bruce Eckel says?

    <Thinking in java> chapter 7 :
    Even though constructors are not polymorphic (they?re actually static methods, but the static declaration is implicit), it?s important ...
    Are constructors actually static methods? I do not think so. static method can only manipulate static members, but constructor can also deal with non-static members. In other words, constructor always associate with a object, while static method always associate with a class.
    Why Mr. Eckel says that constructors are static?

    From the JLS ?8.8.3
    A constructor is always invoked with respect to an object, so it makes no sense for a constructor to be static, so no they are not.
    Are constructors actually static methods?Constructor declarations are not members. Members are defined as the set fields, methods, nested classes and interfaces(JLS ?8). So they are not methods.

  • Advantages and disadvanteges with static methods

    Hi,
    Can anybody suggest me the advantages and disadvantages of static methods? In my project i am using templates which are used by different programs and in that templates i am using static methods.
    It is web application. is there any problems if made methods as static in templates that are used by diferent clients?
    Thanks
    Karimulla

    A static method can't be overridden, and static methods are usually only used for some utility methods and other things which don't belong to the class. I would probably not make the methods static.
    Kaj

  • JUnit : How to Mock Static Method

    Hi,
    I was using EasyMock to write Junit for the methods of the class.
    The Limitation of this library is that only Interfaces can be mocked without any much effort and behavior can be set according to our needs.
    Since, now we need to mock even normal classes, I got mocuer library from net and this too is easy to implement. The problem / limitation is that, I cant mock static methods of a class.
    Is there is any workaround / library so that even static methods can be mocked??.
    Advance thanks.

    Since you would like to mock the static method, it is not part of the class you'd like to test, I assume. The class you do want to test is supposedly under your control and contains the static invocation. I'd suggest to refactor the use of the static invocation in the class being tested.
    I see two approaches:
    1. wrap the static method call in an instance of newly created service class.
       public class ServiceMethodWrapperImpl implements ServiceMethodWrapper {
           public int serviceCall(String arg) {
             return OtherClass.staticMethod(arg);
       }and then mock the ServiceMethoWrapper interface for testing
    2. wrap the static call in a protected method of the class under test. In you test case, test a derived class in which you override the method that calls the service to use a mock:
       public class TestedClass {
         protected int callStaticMethod(String arg) {
             return OtherClass.staticMethod(arg);
         public void something() {
             // replaced OtherClass.staticMethod by
             if (callStaticMethod("Sun") == 3) {
       public void testSomethingForTheClass() {
          TestedClass instance = new TestedClass() {
               protected int callStaticMethod(String arg) {
                    return 3; // mocked answer
       }

Maybe you are looking for

  • Apple id showing up on another phone

    my husband and i each have an i phone, each with our own apple Id,  but my apple id is showing up on his phone.how does this happen and how do i fix it

  • What is "grow" command in Photoshop CC 2014?

    Photoshop CC 2014 Windows 8.1 What is "grow" command in Photoshop CC 2014?

  • Ui control in insertion palette

    Hi, I am using TestStand 4.2.1, not Labview. In the help, I have read that Ui Control like ListBox or ListBar are available but they are not displayed in insertion palette. How can I display them or add them programmatically to my sequence ? Thank yo

  • Flash CS3 crashing at startup

    Man. I've never been so disappointed in a company relating to its technical support. First off, I just wrote a new post (few hours ago) about a Flash problem that it crashed during startup. I'm still having this problem. But the big issue now is that

  • How to make speed up movie clips?

    Let's say I take a movie of my daughter cleaning her room (45 min.)...but I want it to look like she did it in 20 sec! Make it look like she's zooming around the room? I've seen it in movies, but not sure how to do it myself? Would also like to attac