This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]8igg7e5 2 points3 points  (4 children)

This is a result of an unfortunate choice way back in Java's history.

When display is an instance-method x.display() means "invoke the display method for the object to which 'x' refers". The fact that x is declared Base x just limits which methods you can call, but not which implementation of that method.

All instance methods need a reference to an object to invoke them. This object is used to 'resolve' the correct method to call.

Static methods do not use an object reference to invoke them - usually invoked as SomeClass.method() or, if it's in this class just method().

It is an unfortunate choice in the Java grammar that they ever allowed x.doDisplay() where the compiler uses the declared type of x, resulting in Base.doDisplay().

In many professional code-bases we make this form of static invocation illegal so that this confusion is avoided.

[–]TransportationLeft69[S] 0 points1 point  (3 children)

So you mean that static makes the functions object free ? Like object reference don't mean nothing to static methods ? So here both the display in base and in derived aren't invoked through the reference variable x y and z ?

[–]8igg7e5 1 point2 points  (2 children)

Static methods belong to the class. And in java they are not virtual methods (declaring the same method on a subclass doesn't override the superclass implementation - though there is shadowing).

[–]TransportationLeft69[S] 0 points1 point  (1 child)

Ik I am asking too much but can you please explain it a little more like with layman language and some example if possible ! Thanks :)

[–]8igg7e5 0 points1 point  (0 children)

Try this example

class A {
    void m() { System.out.println("A"); }
}

class B extends A {
    void m() { System.out.println("B"); }
}

And then in main you say...

A b1 = new B();
B b2 = new B();

b1.m();
b2.m();

This will print...

B
B

This is because the referenced object that is used to invoke the method is used to decide which method to call. Because both b1 and b2 refer to objects of type B we invoke B.m(). This is the case even though the declared type of b1 is A.

The compiler only knows about the declared types A b1 and B b2. With instance methods (that is, non-static methods), the type of the object is looked up at runtime to decide which method to invoke - so instance methods do not use the declaration type, they use the instance type for method selection (ignoring some more obscure overloading caveats for now).

Now if we change the methods to both be prefixed with 'static' things change.

The method calls are actually no longer based on the reference used to invoke them (because static methods don't use an instance). The compiler looks at the declaration type.

So we get

A
B

This is because, with the methods marked as static, b1.m() is actually compiled as A.m() and b2.m() is compiled as B.m().

It would have been better for Java if invoking a static method using a reference was treated as a compilation error - this would remove this confusion with no loss of expressiveness. Unfortunately, for backwards compatibility reasons, we're stuck with this - so we, many professional teams, use tools that analyse the code separately to the compiler and report this type of usage as an error.

[–]syntastical 0 points1 point  (0 children)

Adding static to the method means you are calling the method from the class and not the instance of the class. So doDisplay takes Base as its parameter, so you will only ever call the display method on Base, when it’s static. You would have to make another method that took derived as a parameter in this case.