Abstract class in Java - method overriding [duplicate] - java

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
If static methods can't be overridden, how its working here (For Java)?
(3 answers)
Why doesn't the compiler complain when I try to override a static method?
(9 answers)
Closed 4 years ago.
I have started learning Java, and have come across this example, on this page:
abstract class Writer {
public static void write() {
System.out.println("Writing...");
}
}
class Author extends Writer {
public static void write() {
System.out.println("Writing book");
}
}
public class Programmer extends Writer {
public static void write() {
System.out.println("Writing code");
}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}
Of the options available for the result of this code, it says that the right answer is:
Writing...
How does it work exactly then, I thought the methods we write in the class that extends abstract class override the methods in the abstract class, but here the answer suggest otherwise.

Related

concrete method in abstract class and default method in interface having the same name [duplicate]

This question already has answers here:
Significance of inheriting method from superclass instead of default method from implementing interface in java 8
(2 answers)
Java8: Why is it forbidden to define a default method for a method from java.lang.Object
(5 answers)
Closed 1 year ago.
I have declared the default method and concrete method in the abstract class with the same name.
public class AbstractClassDefaultMethodTest {
public static void main(String[] args) {
DemoInterface testDefaultMethods=new TestDefaultMethods();
testDefaultMethods.display();
}
}
abstract class DemoClass{
public void display()
{
System.out.println("Inside display method of abstract class");
}
}
interface DemoInterface{
public default void display()
{
System.out.println("Inside display method of interface");
}
}
class TestDefaultMethods extends DemoClass implements DemoInterface
{
}
Why the concrete method of abstract class is getting called? Why we are not getting the compile time error, as both the method names are same ?

Method Calls Not Working [duplicate]

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
The method calls at the end of the main method are giving me an error saying "non-static method cannot be referenced from a static context" I'm not sure what I'm doing wrong in the method call.
public static void main(String[] args)
{
ArrayList<Candidate> voteCount = new ArrayList<Candidate>();
//add objects to voteCount
printListResults(voteCount);
totalListVotes(voteCount);
printListTable(voteCount);
}
public void printListResults(ArrayList<Candidate> election)
{
//some code
}
public int totalListVotes(ArrayList<Candidate> election)
{
//some code
}
public void printListTable(ArrayList<Candidate> election)
{
//some code
}
You simply need to declare these methods as static
public static void printListResults(ArrayList<Candidate> election) {
//some code
}
public static int totalListVotes(ArrayList<Candidate> election) {
//some code
}
public static void printListTable(ArrayList<Candidate> election) {
//some code
}
An alternative approach would be to instantiate an object of your class, as pointed out in the answer from JoschJava. Either way will work. Which approach you choose is partly a matter of taste and partly depends upon the needs of your application (which is beyond the scope of this question).
The problem is that you're trying to call a class method from a static method. You need to instantiate your class:
YourClass classObj = new YourClass();
classObj.printListResults(voteCount);

Why is superclass method called while that method is overriden? (from OCA practice test) [duplicate]

This question already has answers here:
Why doesn't Java allow overriding of static methods?
(22 answers)
Closed 5 years ago.
From question three in these OCA practice questions (pdf):
abstract class Writer {
public static void write() {
System.out.println("Writing...");
}
}
class Author extends Writer {
public static void write() {
System.out.println("Writing book");
}
}
public class Programmer extends Writer {
public static void write() {
System.out.println("Writing code");
}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}
The output is Writing....
I don't understand why. As Programmer overrides Writer's write method, I thought it should call the method in Programmer and not in Writer.
Why?
You have to understand two points here.
There is no overriding concept in case of static members. They are simply static and never change based on instance.
And static members bind to class rather than instance. So no matter what is the instance, they look the type they got called and execute.
The type of the reference is Writer. You have called a static method for which overriding isn't applied - the method from the Writer is going to be invoked.
The mechanism is called method hiding.
Check out these cases:
new Programmer().write(); // code [Programmer]
((Writer)new Author()).write(); // ... [Writer]
new Author().write(); // book [Author]
((Writer)new Programmer()).write(); // ... [Writer]
new Writer() {{}}.write(); // ... [Writer]
As we know, static methods cannot be overridden. If we try to do so, it turns out to be method hiding instead. In the above case, both class- Writer and Programmer contain write() method.
When Programmer extends the Writer class and provides its own implementation of the write() method, it just hides the Writer implementation of it.
Now, on runtime, the compiler just checks the Reference type (since it is a static method, compiler is not concerned about the object created to call the method. Remember, static methods are class methods). Hence, compiler checks and finds that reference w is of type Writer, it calls the Writer version of the write method instead.
If the methods would not have been static, what you expect would have been the output instead.
Found the answer myself.
There is no such thing as overriding a static method in Java. This is why when you call a static method from the superclass reference, the superclass static method will be called.
So
public class SuperClass {
public static void write() {
System.out.println("Writing Super");
}
public void writeMore() {
System.out.println("super something");
}
}
public class SubClass extends SuperClass {
public static void write() {
System.out.println("Writing Sub");
}
public void writeMore() {
System.out.println("sub something");
}
}
public class Test {
public static void main(String[] args) {
SuperClass super = new SubClass();
super.write();
super.writeMore();
}
}
Will output
Writing super
sub something
If you want to call the static write() method from the subclass. You have to reference it from a subclass. E.g.:
SubClass sub = new Subclass();
sub.write();
Some sources where I learned about this:
https://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
Why doesn't Java allow overriding of static methods?

a function is required to be static in java [duplicate]

This question already has answers here:
cannot make a static reference to a non static method
(5 answers)
Closed 7 years ago.
The following block has an error. It requires the createArrayList function to be static. I cannot understand the reason. I appreciate if anyone can explains that to me in an understandable way.
import java.util.ArrayList;
public class Ceasefire {
public static void main(String[] args)
{
createArrayList();
System.exit(0);
}
public void createArrayList()
{
ArrayList<String> aL1 = new ArrayList<String>();
aL1.add("Item1");
aL1.add("Item2");
aL1.add("Item3");
System.out.println(aL1);
}
}
You cannot call a non-static (createArrayList) method from a static one (main). A static method can only call other static methods, but no instance methods.

Why this code yields false for final modifier? [duplicate]

This question already has answers here:
Anonymous Inner classes and Final modifier [duplicate]
(3 answers)
Closed 5 years ago.
this is rather a theoretical question but maybe you know the specification that deep that will let you answer... Why this code yields false in terms of if the anonymous class is final? In practice the class can be considered final (there is no way to extend it without bytecode manipulation):
public class Modifiers
{
public static void main(final String[] args) throws ClassNotFoundException
{
new Modifiers().go();
}
public void go() throws ClassNotFoundException
{
final Runnable r = new Runnable()
{
#Override
public void run()
{
System.out.println("Inside runnable");
}
};
r.run();
System.out.println(Modifier.isFinal(getClass().getClassLoader().loadClass(Modifiers.class.getName() + "$1").getModifiers()));
}
}
Because the anonymous inner class that you are checking, Modifiers$1, is not final.
The variable r is final, but that does not mean that the class itself is final.

Categories