Can we use static method in an abstract class? - java

In Java Programming, Can we call a static method of an abstract class?
Yes I know we can't use static with a method of an abstract class. but I want to know why.. ?

In Java you can have a static method in an abstract class:
abstract class Foo {
static void bar() { }
}
This is allowed because that method can be called directly, even if you do not have an instance of the abstract class:
Foo.bar();
However, for the same reason, you can't declare a static method to be abstract. Normally, the compiler can guarantee that an abstract method will have a real implementation any time that it is called, because you can't create an instance of an abstract class. But since a static method can be called directly, making it abstract would make it possible to call an undefined method.
abstract class Foo {
abstract static void bar();
}
// Calling a method with no body!
Foo.bar();
In an interface, all methods are implicitly abstract. This is why an interface cannot declare a static method. (There's no architectural reason why an interface couldn't have a static method, but I suspect the writers of the JLS felt that that would encourage misuse of interfaces)

If you are talking about java, answer is Yes But you need to define the static method. You cannot create an abstract static method. What you can create is non abstract static method.
Reason is you do not need a object instance to access a static method, so you need the method to be defined with a certain functionality.
so you cannot have,
abstract class AbstractClassExample{
abstract static void method();
}
But you can have,
abstract class AbstractClassExample{
static void method(){}
}
Hope this helps...

Here is a simple explanation.Abstract methods must be implemented later.We know that static methods cannot be overridden because static methods do not belong to any particular instance, rather it belongs to the class.Then different implementation of abstract method,which is static, in different classes is counter-intuitive.

Yes, of course you can define the static method in abstract class.
you can call that static method by using abstract class,or by using child class who extends the abstract class.Also you can able to call static method through child class instance/object.
To illustrate further test following example.
//Parent class
public abstract class TestAbstractClass {
static void testStaticMethod(){
System.out.println("In Parent class static method");
}
}
//child class
public class ChildClass extends TestAbstractClass {
public static void main(String[] args) {
TestAbstractClass parentObj = new ChildClass();
parentObj .testStaticMethod();
ChildClass childObj = new ChildClass();
childObj.testStaticMethod();
TestAbstractClass.testStaticMethod();
childClass.testStaticMethod();
}
}

From Java 9 onwards you can have static methods in an interface. However, the implementation must be provided in the block itself. Unlike static methods in a class, a static method in an interface is not inherited by implementation through a class or subinterface.
An abstract can contain a static method. It is because a static method though not overridden can be hidden.
But an abstract method cannot be declared static at the same time as an abstract method must be overridden ans implemented by a subclass's method and declaring it static will prevent overriding.
In other words, you cannot use abstract and static keywords to declare the same method. However, you can have a static method inside an abstract class.

Related

#Override on static methods? [duplicate]

I'd like to know:
Why can't static methods be overridden in Java?
Can static methods be overloaded in Java?
Static methods can not be overridden in the exact sense of the word, but they can hide parent static methods
In practice it means that the compiler will decide which method to execute at the compile time, and not at the runtime, as it does with overridden instance methods.
For a neat example have a look here.
And this is java documentation explaining the difference between overriding instance methods and hiding class (static) methods.
Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and
not on the compile time type of it (which is the case with overriden
static methods)
Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of
overriding it. Even if you add another static method in a subclass,
identical to the one in its parent class, this subclass static method
is unique and distinct from the static method in its parent class.
Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example
static class Class1 {
public static int Method1(){
return 0;
}
}
static class Class2 extends Class1 {
public static int Method1(){
return 1;
}
}
public static class Main {
public static void main(String[] args){
//Must explicitly chose Method1 from Class1 or Class2
Class1.Method1();
Class2.Method1();
}
}
And yes static methods can be overloaded just like any other method.
Static methods cannot be overridden because they are not dispatched on the object instance at runtime. The compiler decides which method gets called.
This is why you get a compiler warning when you write
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod()
// because it is not dispatched on myObject
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
Static methods can be overloaded (meaning that you can have the same method name for several methods as long as they have different parameter types).
Integer.parseInt("10");
Integer.parseInt("AA", 16);
Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.
Static methods can not be overridden because they are not part of the object's state. Rather, they belongs to the class (i.e they are class methods). It is ok to overload static (and final) methods.
Overloading is also called static binding, so as soon as the word static is used it means a static method cannot show run-time polymorphism.
We cannot override a static method but presence of different implementations of the same static method in a super class and its sub class is valid. Its just that the derived class will hide the implementations of the base class.
For static methods, the method call depends on the type of reference and not which object is being referred, i.e. Static method belongs only to a class and not its instances , so the method call is decided at the compile time itself.
Whereas in case of method overloading static methods can be overloaded iff they have diff number or types of parameters. If two methods have the same name and the same parameter list then they cannot be defined different only by using the 'static' keyword.
If I m calling the method by using SubClass name MysubClass then subclass method display what it means static method can be overridden or not
class MyClass {
static void myStaticMethod() {
System.out.println("Im in sta1");
}
}
class MySubClass extends MyClass {
static void myStaticMethod() {
System.out.println("Im in sta123");
}
}
public class My {
public static void main(String arg[]) {
MyClass myObject = new MyClass();
myObject.myStaticMethod();
// should be written as
MyClass.myStaticMethod();
// calling from subclass name
MySubClass.myStaticMethod();
myObject = new MySubClass();
myObject.myStaticMethod();
// still calls the static method in MyClass, NOT in MySubClass
}
}
No,Static methods can't be overriden as it is part of a class rather than an object.
But one can overload static method.
Static methods are a method whose single copy is shared by all the objects of the class. A static method belongs to the class rather than objects. since static methods are not dependent on the objects, Java Compiler need not wait till the creation of the objects so to call a static method we use syntax like ClassName.method() ;
In the case of method overloading, methods should be in the same class to overload.even if they are declared as static it is possible to overload them as,
Class Sample
{
static int calculate(int a,int b,int c)
{
int res = a+b+c;
return res;
}
static int calculate(int a,int b)
{
int res = a*b;
return res;
}
}
class Test
{
public static void main(String []args)
{
int res = Sample.calculate(10,20,30);
}
}
But in the case of method overriding, the method in the super class and the method in the sub class act as a different method. the super class will have its own copy and the sub class will have its own copy so it does not come under method overriding.
class SuperType {
public static void classMethod(){
System.out.println("Super type class method");
}
public void instancemethod(){
System.out.println("Super Type instance method");
}
}
public class SubType extends SuperType{
public static void classMethod(){
System.out.println("Sub type class method");
}
public void instancemethod(){
System.out.println("Sub Type instance method");
}
public static void main(String args[]){
SubType s=new SubType();
SuperType su=s;
SuperType.classMethod();// Prints.....Super type class method
su.classMethod(); //Prints.....Super type class method
SubType.classMethod(); //Prints.....Sub type class method
}
}
This example for static method overriding
Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.
Static method belongs to class only.
static methods are class level methods.
Hiding concept is used for static methods.
See : http://www.coderanch.com/how-to/java/OverridingVsHiding
The very purpose of using the static method is to access the method of a class without creating an instance for it.It will make no sense if we override that method since they will be accessed by classname.method()
No, you cannot override a static method. The static resolves against the class, not the instance.
public class Parent {
public static String getCName() {
return "I am the parent";
}
}
public class Child extends Parent {
public static String getCName() {
return "I am the child";
}
}
Each class has a static method getCName(). When you call on the Class name it behaves as you would expect and each returns the expected value.
#Test
public void testGetCNameOnClass() {
assertThat(Parent.getCName(), is("I am the parent"));
assertThat(Child.getCName(), is("I am the child"));
}
No surprises in this unit test. But this is not overriding.This declaring something that has a name collision.
If we try to reach the static from an instance of the class (not a good practice), then it really shows:
private Parent cp = new Child();
`enter code here`
assertThat(cp.getCName(), is("I am the parent"));
Even though cp is a Child, the static is resolved through the declared type, Parent, instead of the actual type of the object. For non-statics, this is resolved correctly because a non-static method can override a method of its parent.
You can overload a static method but you can't override a static method. Actually you can rewrite a static method in subclasses but this is not called a override because override should be related to polymorphism and dynamic binding. The static method belongs to the class so has nothing to do with those concepts. The rewrite of static method is more like a shadowing.
I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-
class Class1 {
public static int Method1(){
System.out.println("true");
return 0;
}
}
class Class2 extends Class1 {
public static int Method1(){
System.out.println("false");
return 1;
}
}
public class Mai {
public static void main(String[] args){
Class2 c=new Class2();
//Must explicitly chose Method1 from Class1 or Class2
//Class1.Method1();
c.Method1();
}
}
It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.
The best answer i found of this question is:
http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/
As any static method is part of class not instance so it is not possible to override static method
From Why doesn't Java allow overriding of static methods?
Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.
There were two considerations driving Java's design that impacted this. One was a concern with performance: there had been a lot of criticism of Smalltalk about it being too slow (garbage collection and polymorphic calls being part of that) and Java's creators were determined to avoid that. Another was the decision that the target audience for Java was C++ developers. Making static methods work the way they do have the benefit of familiarity for C++ programmers and were also very fast because there's no need to wait until runtime to figure out which method to call.
Definitely, we cannot override static methods in Java.
Because JVM resolves correct overridden method based upon the object at run-time by using dynamic binding in Java.
However, the static method in Java is associated with Class rather than the object and resolved and bonded during compile time.

Making multiple classes with the same named static method

Imagine having the classes:
public class classA {
public static String name() {
return "classA";
}
}
public class classB {
public static String name() {
return "classB";
}
}
Since both classes have the same-named static method, I would like to make something like a parent element that they would relate to that would declare that all its child would implement a static method name().
Using interfaces is impossible since I don't want the declaration of the static method to be inside the interface and static methods cannot be overridden. Also, using an abstract class is also not a solution since I can't declare an abstract static method.
Is there a way of doing what I would want to?
You can't enforce parent child relation using static keyword so no there is no way of doing this.
To be implemented by a child class, name() method should be abstract. Which isn't possible as it is static. Also study about the implications of inheriting static methods : Are static methods inherited in Java?

Java: Abstract Class Invocation via Main Method

Okay, people are probably going to run to flag this as a duplicate, just by reading the title and without really reading the question. So please know that I HAVE tried to look at other questions on this platform, but have not found something that clears my doubts exactly. Kindly allow me to reach out and ask my question. Thanks in advance.
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
I do not completely understand the latter part of the statement. Is this talking about the main method being directly within the abstract class itself ? Is it talking about invoking the abstract class via a child's main method ? Or both ?
Secondly, I have seen examples like the following.
abstract class Printer
{
public void print() { … };
}
public class TestPrinter
{
public static void main( String[] args )
{
// use of anonymous class
final Printer p = new Printer()
{
#override
public void print()
{
...
}
}
}
}
And have been told that an anonymous class is at work. But, I seriously do not understand how, since the variable 'p' is clearly being assigned to... and it's an abstract class variable!! How is that even possible? I thought abstract classes can not be instantiated or initialized.
Any help would be appreciated.
final Printer p = new Printer()
{
#override
public void print()
{
...
}
}
This means that an anonymous class is created which extends Printerand the variable p is referring to subclass instance.
This is simply polymorphism in action. By creating anonymous class here, you are creating a subclass of Printer and using polymorphism you are using the superclass reference variable p to refer to object of subclass which is anonymous but extends Printer because of the syntax below
Printer p = new Printer(){...}
and this is not only limited to abstract class, you can also create an anonymous class which implements and interface. Consider below example.
package com.test;
public interface SomeInterface {
public void SomeMethod();
}
and a class below
package com.test;
public class TestAnonymous {
public static void main(String[] args) {
SomeInterface obj = new SomeInterface() {
#Override
public void SomeMethod() {
System.out
.println("Yaayy!!! Creating an anonymous class which implements SomeInterface ");
}
};
obj.SomeMethod();
}
}
which prints out
Yaayy!!! Creating an anonymous class which implements SomeInterface
What is means that the syntax creates an anonymous class which either extends the abstract class or implements the interface of which reference variable is used to instantiate. It calls method of the subclass.
You can refer jsl.https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.1
Now your question
Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists
What I understand from your questions is whether you want to know whether main method can be run in abstract class without instantiating it, The answer is YES
package com.test;
public abstract class AbstractClass {
public static void main(String[] args) {
System.out.println("main method in abstract class");
}
}
compile and invoke it using java AbstractClass and it should print
main method in abstract class
IF you want to know whether the abstract class constructor is invoked when instantiating the anynomous class or not, then also the answer is YES.
Whenver a subclass constructor is called, it invokes super class constructor by making a super() call. So abstract class constructor will also get called.
http://www.thejavageek.com/2013/07/21/initialization-blocks-constructors-and-their-order-of-execution/
An abstract class is just like any other class - except for the fact that it cannot be instantiated directly. I presume you know the use for such a facility. Hence it can very well have a main(), which is a static method, not an instance method
The anonymous class in your example, extends the abstract class (or implements an interface, if one is specified). So p is not assigned to an abstract class instance, but to an instance of a class which extends the abstract class
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
It is nonsense. Any static method of an abstract class can be invoked. Not just main().
Secondly, I have seen examples like the following ... and have been told that an anonymous class is at work.
That is correct.
But, I seriously do not understand how, since the variable 'p' is clearly being assigned to... and it's an abstract class variable!! How is that even possible? I thought abstract classes can not be instantiated or initialized.
It is the anonymous class that is being instantiated here, which extends the abstract class, and provides an implementation of the abstract method. The reference to that class is being stored into Person p, because Person is a superclass of the anonymous class. You can do that for any other class or interface. There's nothing new here.
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
Since main() method is static an can be invoked without instantiation. e.g.
abstract class AbstractClass{
public static void main(String[] args){
}
}
The same was not true for interface till Java7, With Java8 you can have static main method inside interface hence same would be true for Java8
You second question, while creating an instance of Printer you have defined the sub-class of Printer as well but you can not use this defined implementation of Printer again(since there is no name associated with the implementation), Hence, its anonymous.

Abstract class having a main?

Would using a main for an abstract class be bad practice in general or is it permissible due to the nature of Abstract classes being able to have a body?
Sure, an abstract class can have a main method, just as any class can have a main, and in fact it is one way of testing the abstract class -- if you create a concrete implementation of it within the main method. The only thing that you cannot do with an abstract class is to construct them as is, without extending them and implementing all abstract methods.
public abstract class Foo {
public abstract void bar();
public static void main(String[] args) {
// anonymous inner class representation
Foo foo = new Foo() {
// must implement all abstract methods
public void bar() {
System.out.println("bar");
}
};
foo.bar();
}
}
Edit: good point by VitalyGreck:
abstract classes are abstract because they don't implement some methods in their body. having bar() implemented inside the main() method (even static) confuses users of your class. Good practice is to make two separate classes, one of them - abstract, another - with implementation and static method enclosed. Or dynamically find the enclosing class (see stackoverflow.com/questions/936684/…) using reflection.
In other words -- just because it can be done, doesn't mean that it should be done.
You have no problemas having a main in your abstract class.
Static methods does not override, any subclass can also have the same static method.

What is the use of main method in abstract class?

I know that we can write main method in abstract class, but what we can achieve from it ?
public abstract class Sample
{
public static void main(String args[])
{
System.out.println("Abstract Class main method : ");
}
}
We can not create the object of abstract class ,so what is the use of main method in abstract class ?
Abstract just means you can't instantiate the class directly.
Loading a class is not the same as creating an instance of the class. And there's no need to create an instance of the class to call main(), because it's static. So there's no problem.
Abstract just means you can't instantiate the class directly. You can have constructors if you want - they might be needed for subclasses to initiate the object state. You can have static methods, including main() and they don't need an object so calling them is fine.
So you only got error when you try to create the object, which is when you run into the abstract limitation.
You can extend the abstract class and then the child class has a main method without specifying one there.
public abstract class Abstrc
{
Abstrc(){} // constructor
public abstract void run(); // abstract method
public static int mul(){return 3*2;} // static method
public static void main(String[] args)
{ // Static method that can be accessed without instantiation
System.out.println("Your abstract no is : " + Abstrc.mul());
}
}
Your abstract no is : 6
As Zeeshan already said, since the main method is static, it does not require an instance to be called. As to what can be achieved by placing the main method in an abstract class, well nothing more or less than placing it in any other class.
Typically, the main method is either placed in a class of its own or in a class that is central to the application. If that class happens to be abstract, so be it.

Categories

Resources