Polymorphism and inheritance in Java with static methods of abstract class

Polymorphism and inheritance in Java with static methods of abstract class



I was going through the sample questions of Java 8 Programmer I exam on Oracle website and came across the following question:


abstract class Writer
public static void write()
System.out.println("Writing...");


class Author extends Writer
public static void write()
System.out.println("Writing book");


class Programmer extends Writer
public static void write()
System.out.println("Writing code");

public static void main(String args)
Writer w = new Author();
w.write();//What would be the ouput here?




The correct answer is that the method of the abstract class is called.



Now, my understanding was that in polymorphism, if a variable of type parent class contains a reference to an object of subclass, then the method of the subclass will be called.



Therefore, am I understanding right that in case of a static function, the method of the of the class whose variable contains the refrence would be called?






I appreciate the quick accept!

– GhostCat
Sep 10 '18 at 3:43




2 Answers
2



There is no polymorphism for static methods.



The compiler decides at compile time which method is going to be invoked.



It sees that w is a Writer, and it does neither know or care that the actual instance will be of that specific sub class at runtime. The compiler could know it sometimes, but Java takes the easy path here.



That is one of the reasons why you are really careful about using static methods in real world production code: doing so means sacrificing one of the essential elements of OOP.



Nope, you can't override static methods in a subclass, so there's no polymorphic runtime lookup of the method. Static methods have no interaction with instance fields/methods of the class, so making a call to a static method dependent on a particular instance/subclass wouldn't make sense.



It's easier to think of static methods as just utility/library methods. And they are contained within classes just for the purpose of organization.



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế