The question is in Java why can't I define an abstract static method? for example
abstract class foo {
abstract void bar( ); // <-- this is ok
abstract static void bar2(); //<-- this isn't why?
}
Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction.
Poor language design. It would be much more effective to call directly a static abstract method than creating an instance just for using that abstract method. Especially true when using an abstract class as a workaround for enum inability to extend, which is another poor design example. Hope they solve those limitations in a next release.
You can't override a static method, so making it abstract would be meaningless. Moreover, a static method in an abstract class would belong to that class, and not the overriding class, so couldn't be used anyway.
The abstract annotation to a method indicates that the method MUST be overriden in a subclass.
In Java, a static member (method or field) cannot be overridden by subclasses (this is not necessarily true in other object oriented languages, see SmallTalk.) A static member may be hidden, but that is fundamentally different than overridden.
Since static members cannot be overriden in a subclass, the abstract annotation cannot be applied to them.
As an aside - other languages do support static inheritance, just like instance inheritance. From a syntax perspective, those languages usually require the class name to be included in the statement. For example, in Java, assuming you are writing code in ClassA, these are equivalent statements (if methodA() is a static method, and there is no instance method with the same signature):
ClassA.methodA();
and
methodA();
In SmallTalk, the class name is not optional, so the syntax is (note that SmallTalk does not use the . to separate the "subject" and the "verb", but instead uses it as the statemend terminator):
ClassA methodA.
Because the class name is always required, the correct "version" of the method can always be determined by traversing the class hierarchy. For what it's worth, I do occasionally miss static inheritance, and was bitten by the lack of static inheritance in Java when I first started with it. Additionally, SmallTalk is duck-typed (and thus doesn't support program-by-contract.) Thus, it has no abstract modifier for class members.
I also asked the same question , here is why
Since Abstract class says, it will not give implementation and allow subclass to give it
so Subclass has to override the methods of Superclass ,
RULE NO 1 - A static method cannot be overridden
Because static members and methods are compile time elements , that is why Overloading(Compile time Polymorphism) of static methods are allowed rather then Overriding (Runtime Polymorphism)
So , they cant be Abstract .
There is no thing like abstract static <--- Not allowed in Java Universe
This is a terrible language design and really no reason as to why it can't be possible.
In fact, here is a pattern or way on how it can be mimicked in **Java ** to allow you at least be able to modify your own implementations:
public static abstract class Request {
// Static method
public static void doSomething() {
get().doSomethingImpl();
}
// Abstract method
abstract void doSomethingImpl();
/////////////////////////////////////////////
private static Request SINGLETON;
private static Request get() {
if ( SINGLETON == null ) {
// If set(request) is never called prior,
// it will use a default implementation.
return SINGLETON = new RequestImplementationDefault();
}
return SINGLETON;
}
public static Request set(Request instance){
return SINGLETON = instance;
}
/////////////////////////////////////////////
}
Two implementations:
/////////////////////////////////////////////////////
public static final class RequestImplementationDefault extends Request {
#Override void doSomethingImpl() {
System.out.println("I am doing something AAA");
}
}
/////////////////////////////////////////////////////
public static final class RequestImplementaionTest extends Request {
#Override void doSomethingImpl() {
System.out.println("I am doing something BBB");
}
}
/////////////////////////////////////////////////////
Could be used as follows:
Request.set(new RequestImplementationDefault());
// Or
Request.set(new RequestImplementationTest());
// Later in the application you might use
Request.doSomething();
This would allow you to invoke your methods statically, yet be able to alter the implementation say for a Test environment.
Theoretically, you could do this on a ThreadLocal as well, and be able to set instance per Thread context instead rather than fully global as seen here, one would then be able to do Request.withRequest(anotherRequestImpl, () -> { ... }) or similar.
Real world usually do not require the ThreadLocal approach and usually it is enough to be able to alter implementation for Test environment globally.
Note, that the only purpose for this is to enable a way to retain the ability to invoke methods DIRECTLY, EASILY and CLEANLY which static methods provides while at the same time be able to switch implementation should a desire arise at the cost of slightly more complex implementation.
It is just a pattern to get around having normally non modifiable static code.
An abstract method is defined only so that it can be overridden in a subclass. However, static methods can not be overridden. Therefore, it is a compile-time error to have an abstract, static method.
Now the next question is why static methods can not be overridden??
It's because static methods belongs to a particular class and not to its instance. If you try to override a static method you will not get any compilation or runtime error but compiler would just hide the static method of superclass.
A static method, by definition, doesn't need to know this. Thus, it cannot be a virtual method (that is overloaded according to dynamic subclass information available through this); instead, a static method overload is solely based on info available at compile time (this means: once you refer a static method of superclass, you call namely the superclass method, but never a subclass method).
According to this, abstract static methods would be quite useless because you will never have its reference substituted by some defined body.
I see that there are a god-zillion answers already but I don't see any practical solutions. Of course this is a real problem and there is no good reason for excluding this syntax in Java. Since the original question lacks a context where this may be need, I provide both a context and a solution:
Suppose you have a static method in a bunch of classes that are identical. These methods call a static method that is class specific:
class C1 {
static void doWork() {
...
for (int k: list)
doMoreWork(k);
...
}
private static void doMoreWork(int k) {
// code specific to class C1
}
}
class C2 {
static void doWork() {
...
for (int k: list)
doMoreWork(k);
...
}
private static void doMoreWork(int k) {
// code specific to class C2
}
}
doWork() methods in C1 and C2 are identical. There may be a lot of these calsses: C3 C4 etc. If static abstract was allowed, you'd eliminate the duplicate code by doing something like:
abstract class C {
static void doWork() {
...
for (int k: list)
doMoreWork(k);
...
}
static abstract void doMoreWork(int k);
}
class C1 extends C {
private static void doMoreWork(int k) {
// code for class C1
}
}
class C2 extends C {
private static void doMoreWork(int k) {
// code for class C2
}
}
but this would not compile because static abstract combination is not allowed.
However, this can be circumvented with static class construct, which is allowed:
abstract class C {
void doWork() {
...
for (int k: list)
doMoreWork(k);
...
}
abstract void doMoreWork(int k);
}
class C1 {
private static final C c = new C(){
#Override void doMoreWork(int k) {
System.out.println("code for C1");
}
};
public static void doWork() {
c.doWork();
}
}
class C2 {
private static final C c = new C() {
#Override void doMoreWork(int k) {
System.out.println("code for C2");
}
};
public static void doWork() {
c.doWork();
}
}
With this solution the only code that is duplicated is
public static void doWork() {
c.doWork();
}
Assume there are two classes, Parent and Child. Parent is abstract. The declarations are as follows:
abstract class Parent {
abstract void run();
}
class Child extends Parent {
void run() {}
}
This means that any instance of Parent must specify how run() is executed.
However, assume now that Parent is not abstract.
class Parent {
static void run() {}
}
This means that Parent.run() will execute the static method.
The definition of an abstract method is "A method that is declared but not implemented", which means it doesn't return anything itself.
The definition of a static method is "A method that returns the same value for the same parameters regardless of the instance on which it is called".
An abstract method's return value will change as the instance changes. A static method will not. A static abstract method is pretty much a method where the return value is constant, but does not return anything. This is a logical contradiction.
Also, there is really not much of a reason for a static abstract method.
An abstract class cannot have a static method because abstraction is done to achieve DYNAMIC BINDING while static methods are statically binded to their functionality.A static method means
behavior not dependent on an instance variable, so no instance/object
is required.Just the class.Static methods belongs to class and not object.
They are stored in a memory area known as PERMGEN from where it is shared with every object.
Methods in abstract class are dynamically binded to their functionality.
Declaring a method as static means we can call that method by its class name and if that class is abstract as well, it makes no sense to call it as it does not contain any body, and hence we cannot declare a method both as static and abstract.
As abstract methods belong to the class and cannot be overridden by the implementing class.Even if there is a static method with same signature , it hides the method ,does not override it.
So it is immaterial to declare the abstract method as static as it will never get the body.Thus, compile time error.
A static method can be called without an instance of the class. In your example you can call foo.bar2(), but not foo.bar(), because for bar you need an instance.
Following code would work:
foo var = new ImplementsFoo();
var.bar();
If you call a static method, it will be executed always the same code. In the above example, even if you redefine bar2 in ImplementsFoo, a call to var.bar2() would execute foo.bar2().
If bar2 now has no implementation (that's what abstract means), you can call a method without implementation. That's very harmful.
I believe I have found the answer to this question, in the form of why an interface's methods (which work like abstract methods in a parent class) can't be static. Here is the full answer (not mine)
Basically static methods can be bound at compile time, since to call them you need to specify a class. This is different than instance methods, for which the class of the reference from which you're calling the method may be unknown at compile time (thus which code block is called can only be determined at runtime).
If you're calling a static method, you already know the class where it's implemented, or any direct subclasses of it. If you define
abstract class Foo {
abstract static void bar();
}
class Foo2 {
#Override
static void bar() {}
}
Then any Foo.bar(); call is obviously illegal, and you will always use Foo2.bar();.
With this in mind, the only purpose of a static abstract method would be to enforce subclasses to implement such a method. You might initially think this is VERY wrong, but if you have a generic type parameter <E extends MySuperClass> it would be nice to guarantee via interface that E can .doSomething(). Keep in mind that due to type erasure generics only exist at compile time.
So, would it be useful? Yes, and maybe that is why Java 8 is allowing static methods in interfaces (though only with a default implementation). Why not abstract static methods with a default implementation in classes? Simply because an abstract method with a default implementation is actually a concrete method.
Why not abstract/interface static methods with no default implementation? Apparently, merely because of the way Java identifies which code block it has to execute (first part of my answer).
Because abstract class is an OOPS concept and static members are not the part of OOPS....
Now the thing is we can declare static complete methods in interface and we can execute interface by declaring main method inside an interface
interface Demo
{
public static void main(String [] args) {
System.out.println("I am from interface");
}
}
Because abstract mehods always need implementation by subclass.But if you make any method to static then overriding is not possible for this method
Example
abstract class foo {
abstract static void bar2();
}
class Bar extends foo {
//in this if you override foo class static method then it will give error
}
Static Method
A static method can be invoked without the need for creating an instance of a class.A static method belongs to the class rather than the object of a class.
A static method can access static data member and also it can change the value of it.
Abstract Keyword is used to implement abstraction.
A static method can't be overriden or implemented in child class. So, there is no use of making static method as abstract.
The idea of having an abstract static method would be that you can't use that particular abstract class directly for that method, but only the first derivative would be allowed to implement that static method (or for generics: the actual class of the generic you use).
That way, you could create for example a sortableObject abstract class or even interface
with (auto-)abstract static methods, which defines the parameters of sort options:
public interface SortableObject {
public [abstract] static String [] getSortableTypes();
public String getSortableValueByType(String type);
}
Now you can define a sortable object that can be sorted by the main types which are the same for all these objects:
public class MyDataObject implements SortableObject {
final static String [] SORT_TYPES = {
"Name","Date of Birth"
}
static long newDataIndex = 0L ;
String fullName ;
String sortableDate ;
long dataIndex = -1L ;
public MyDataObject(String name, int year, int month, int day) {
if(name == null || name.length() == 0) throw new IllegalArgumentException("Null/empty name not allowed.");
if(!validateDate(year,month,day)) throw new IllegalArgumentException("Date parameters do not compose a legal date.");
this.fullName = name ;
this.sortableDate = MyUtils.createSortableDate(year,month,day);
this.dataIndex = MyDataObject.newDataIndex++ ;
}
public String toString() {
return ""+this.dataIndex+". "this.fullName+" ("+this.sortableDate+")";
}
// override SortableObject
public static String [] getSortableTypes() { return SORT_TYPES ; }
public String getSortableValueByType(String type) {
int index = MyUtils.getStringArrayIndex(SORT_TYPES, type);
switch(index) {
case 0: return this.name ;
case 1: return this.sortableDate ;
}
return toString(); // in the order they were created when compared
}
}
Now you can create a
public class SortableList<T extends SortableObject>
that can retrieve the types, build a pop-up menu to select a type to sort on and resort the list by getting the data from that type, as well as hainv an add function that, when a sort type has been selected, can auto-sort new items in.
Note that the instance of SortableList can directly access the static method of "T":
String [] MenuItems = T.getSortableTypes();
The problem with having to use an instance is that the SortableList may not have items yet, but already need to provide the preferred sorting.
Cheerio,
Olaf.
First, a key point about abstract classes -
An abstract class cannot be instantiated (see wiki). So, you can't create any instance of an abstract class.
Now, the way java deals with static methods is by sharing the method with all the instances of that class.
So, If you can't instantiate a class, that class can't have abstract static methods since an abstract method begs to be extended.
Boom.
As per Java doc:
A static method is a method that is associated with the class in which
it is defined rather than with any object. Every instance of the class
shares its static methods
In Java 8, along with default methods static methods are also allowed in an interface. This makes it easier for us to organize helper methods in our libraries. We can keep static methods specific to an interface in the same interface rather than in a separate class.
A nice example of this is:
list.sort(ordering);
instead of
Collections.sort(list, ordering);
Another example of using static methods is also given in doc itself:
public interface TimeClient {
// ...
static public ZoneId getZoneId (String zoneString) {
try {
return ZoneId.of(zoneString);
} catch (DateTimeException e) {
System.err.println("Invalid time zone: " + zoneString +
"; using default time zone instead.");
return ZoneId.systemDefault();
}
}
default public ZonedDateTime getZonedDateTime(String zoneString) {
return ZonedDateTime.of(getLocalDateTime(), getZoneId(zoneString));
}
}
Because 'abstract' means the method is meant to be overridden and one can't override 'static' methods.
Regular methods can be abstract when they are meant to be overridden by subclasses and provided with functionality.
Imagine the class Foo is extended by Bar1, Bar2, Bar3 etc. So, each will have their own version of the abstract class according to their needs.
Now, static methods by definition belong to the class, they have nothing to do with the objects of the class or the objects of its subclasses. They don't even need them to exist, they can be used without instantiating the classes. Hence, they need to be ready-to-go and cannot depend on the subclasses to add functionality to them.
Because abstract is a keyword which is applied over Abstract methods do not specify a body. And If we talk about static keyword it belongs to class area.
because if you are using any static member or static variable in class it will load at class loading time.
There is one occurrence where static and abstract can be used together and that is when both of these modifiers are placed in front of a nested class.
In a single line, this dangerous combination (abstract + static) violates the object-oriented principle which is Polymorphism.
In an inheritance situation, the JVM will decide at runtime by the implementation in respect of the type of instance (runtime polymorphism) and not in respect of the type of reference variable (compile-time polymorphism).
With #Overriding:
Static methods do not support #overriding (runtime polymorphism), but only method hiding (compile-time polymorphism).
With #Hiding:
But in a situation of abstract static methods, the parent (abstract) class does not have implementation for the method. Hence, the child type reference is the only one available and it is not polymorphism.
Child reference is the only one available:
For this reason (suppress OOPs features), Java language considers abstract + static an illegal (dangerous) combination for methods.
You can do this with interfaces in Java 8.
This is the official documentation about it:
https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
Because if a class extends an abstract class then it has to override abstract methods and that is mandatory. And since static methods are class methods resolved at compile time whereas overridden methods are instance methods resolved at runtime and following dynamic polymorphism.
Related
I was learning through interfaces when I noticed that you can now define static and default methods in an interface.
public interface interfacesample2 {
public static void method() {
System.out.println("hello world");
}
public default void menthod3() {
System.out.println("default print");
}
}
Kindly explain the difference of the two and also if there's an example of when we would use this would be nice. A little confused on Interfaces.
Differences between static and default methods in Java 8:
1) Default methods can be overriden in implementing class, while static cannot.
2) Static method belongs only to Interface class, so you can only invoke static method on Interface class, not on class implementing this Interface, see:
public interface MyInterface {
default void defaultMethod(){
System.out.println("Default");
}
static void staticMethod(){
System.out.println("Static");
}
}
public class MyClass implements MyInterface {
public static void main(String[] args) {
MyClass.staticMethod(); //not valid - static method may be invoked on containing interface class only
MyInterface.staticMethod(); //valid
}
}
3) Both class and interface can have static methods with same names, and neither overrides other!
public class MyClass implements MyInterface {
public static void main(String[] args) {
//both are valid and have different behaviour
MyClass.staticMethod();
MyInterface.staticMethod();
}
static void staticMethod(){
System.out.println("another static..");
}
}
A static method is a method that applies to the class 'namespace', so to speak. So a static method foo of interface Interface is accessed by Interface.foo(). Note that the function call does not apply to any particular instance of the interface.
A default implementation bar on the other hand, is called by
Interface x = new ConcreteClass();
x.bar();
A static interface method cannot know about the this variable, but a default implementation can.
1. explain the difference of the two
Static interface methods are like static class methods(here they belong to Interface only). Where as the default interface methods provide default implementation of interface methods (which implementing classes may override)
But remember in case a class is implementing more than one interface with same default method signature then the implementing class needs to override the default method
You can find a simple example below (can DIY for different cases)
public class Test {
public static void main(String[] args) {
// Accessing the static member
I1.hello();
// Anonymous class Not overriding the default method
I1 t = new I1() {
#Override
public void test() {
System.out.println("Anonymous test");
}
};
t.test();
t.hello("uvw");
// Referring to class instance with overridden default method
I1 t1 = new Test2();
t1.test();
t1.hello("xyz");
}
}
interface I1 {
void test();
//static method
static void hello() {
System.out.println("hello from Interface I1");
}
// default need not to be implemented by implementing class
default void hello(String name) {
System.out.println("Hello " + name);
}
}
class Test2 implements I1 {
#Override
public void test() {
System.out.println("testing 1234...");
}
#Override
public void hello(String name) {
System.out.println("bonjour" + name);
}
}
2. when we would use this would be nice.
That depends on your problem statement. I would say Default methods are useful, if you need same implementation for a method in your specification in all the classes in that contract, Or it may be used like Adapter classes.
here is a good read: https://softwareengineering.stackexchange.com/questions/233053/why-were-default-and-static-methods-added-to-interfaces-in-java-8-when-we-alread
also below oracle doc explains default & static methods for evolving existing interfaces:
Users who have classes that implement interfaces enhanced with new
default or static methods do not have to modify or recompile them to
accommodate the additional methods.
http://docs.oracle.com/javase/tutorial/java/IandI/nogrow.html
Here is my view:
static method in interface:
You can call it directly (InterfacetA.staticMethod())
Sub-class will not be able to override.
Sub-class may have method with same name as staticMethod
default method in interface:
You can not call it directly.
Sub-class will be able to override it
Advantage:
static Method: You don't need to create separate class for utility method.
default Method: Provide the common functionality in default method.
This link has some useful insights, have listed few of them here.
default & static methods have bridged down the differences between interfaces and abstract classes.
Interface default methods:
It helps in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
It helps in extending interfaces without having the fear of breaking implementation classes.
Interface static methods:
They are part of interface, we can’t use it for implementation class objects.
It helps in providing security by not allowing implementation classes to override them.
Like to quote another useful reference.
As per Java14 JLS doc:
Default Method:
It is an instance method declared in an interface with the default
modifier
It can be accessed only by the instance of the implementing class
only
Its body is always represented by a block, which provides a default
implementation or behaviour for any implementing class without
overriding the method
It can never be static or private
Static Method:
It can be invoked by interface without reference to a particular
object, just like class static methods
Static method can be private
The implementing class can not access static method
Lets understand it with the help of below example code:
public interface MyInterface {
private void privateMethod() {
System.out.println("Hi, this is privateMethod");
}
private static void staticPrivateMethod() {
System.out.println("Hi, this is staticPrivateMethod");
}
static void staticMethod() {
//privateMethod(); // Non-static method cannot be referenced from a static contex
System.out.println("Hi, this is staticMethod");
staticPrivateMethod();
}
default void defaultMethod() {
System.out.println("Hi, this is defaultMethod");
}
}
public class MyInterfaceImpl implements MyInterface{
public static void main(String[] args) {
MyInterface.staticMethod();
// myInterface.staticMethod(); // Not allowed
MyInterface myInterface = new MyInterfaceImpl();
myInterface.defaultMethod();
// MyInterface.defaultMethod(); // Not allowed
}
}
According to Oracle's Javadocs: http://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
Normally, static method in interface is used as Helper methods while default method are used as a default implementation for classes that implements that interface.
Example:
interface IDemo {
//this method can be called directly from anywhere this interface is visible
static int convertStrToInt(String numStr) {
return Integer.parseInt(numStr);
}
//getNum will be implemented in a class
int getNum();
default String numAsStr() {
//this.getNum will call the class's implementation
return Integer.toString(this.getNum());
}
}
Interface default methods:
It helps in avoiding utility classes, such as all the Collections class method can be provided in the interfaces itself.
It helps in extending interfaces without having the fear of breaking implementation classes.
Interface static methods:
They are part of interface, we can’t use it for implementation class objects.
It helps in providing security by not allowing implementation classes to override them.
Now how static method providing security. Let's see an example.
interface MyInterface {
/*
* This is a default method so we need not to implement this method in the implementation classes
*/
default void newMethod() {
System.out.println("Newly added default method in Interface");
}
/*
* This is a static method. Static method in interface is similar to default method except that we cannot override them in the implementation classes. Similar to default methods, we need to implement these methods in implementation classes so we can safely add them to the existing interfaces.
*/
static void anotherNewMethod() {
System.out.println("Newly added static method in Interface");
}
/*
* Already existing public and abstract method We must need to implement this method in implementation classes.
*/
void existingMethod(String str);
}
public class Example implements MyInterface {
// implementing abstract method
public void existingMethod(String str) {
System.out.println("String is: " + str);
}
public void newMethod() {
System.out.println("Newly added default method in Class");
}
static void anotherNewMethod() {
System.out.println("Newly added static method in Class");
}
public static void main(String[] args) {
Example obj = new Example();
// calling the default method of class
obj.newMethod();
// calling the static method of class
obj.anotherNewMethod();
// calling the static method of interface
MyInterface.anotherNewMethod();
// calling the abstract method of interface
obj.existingMethod("Java 8 is easy to learn");
}
}
Here obj.newMethod(); printing class implementation logic, means we can change the logic of that method inside implementation class.
But obj.anotherNewMethod(); printing class implementation logic ,but not changed interface implementation. So if any encryption-decryption logic written inside that method you can't change.
we cannot execute Interfacesample2.menthod3(); because it is not static method. In order to execute method3() we need an instance of Interfacesample2 interface.
Please find the following practical example:
public class Java8Tester {
public static void main(String args[]){
// Interfacesample2.menthod3(); Cannot make a static reference to the non-static method menthod3 from the type Interfacesample2
new Interfacesample2(){ }.menthod3();// so in order to call default method we need an instance of interface
Interfacesample2.method(); // it
}
}
interface Interfacesample2 {
public static void method() {
System.out.println("hello world");
}
public default void menthod3() {
System.out.println("default print");
}
}
Starting Java 8 interface can also have static method. Like static method of a class, static method of an interface can be called using Interface name.
Example
public interface Calculator {
int add(int a, int b);
int subtract(int a, int b);
default int multiply(int a, int b) {
throw new RuntimeException("Operation not supported. Upgrade to UltimateCalculator");
}
static void display(String value) {
System.out.println(value);
}
}
Difference between static and default method of interface is default method supports inheritance but static method does not. Default method can be overridden in inheriting interface.
Here is good read about interface default method and static method. Interface Default Method in Java 8
All good answers here. I would like to add another practical usage of the static function in the interface. The tip is coming from the book - Effective Java, 3rd Edition by Joshua Bloch in Chapter2: Creating and Destroying Object.
Static functions can be used for static factory methods.
Static factory method are methods which return an object. They work like constructor. In specific cases, static factory method provides more readable code than using constructor.
Quoting from the book - Effective Java, 3rd Edition by Joshua Bloch
Prior to Java 8, interfaces couldn’t have static methods. By
convention, static factory methods for an interface named Type were
put in a noninstantiable companion class (Item 4) named Types.
Author gives an example of Collections where such static factory method is implemented. Checking on the code, Josh Bloch can be seen as first author of Collections class. Although Collections is a class and not interface. But the concept still applies.
For example, the Java Collections Framework has forty-five utility
implementations of its interfaces, providing unmodifiable collections,
synchronized collections, and the like. Nearly all of these
implementations are exported via static factory methods in one
noninstantiable class (java.util.Collections). The classes of the
returned objects are all nonpublic.
Further he explains that API is not only smaller, it helps with the code readability and API ease..
It is not just the bulk of the API that is reduced but the conceptual
weight: the number and difficulty of the concepts that programmers
must master in order to use the API. The programmer knows that the
returned object has precisely the API specified by its interface, so
there is no need to read additional class documentation for the
implementation class.
Here is one of the static method from java.util.Collections class:
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
return new UnmodifiableCollection<>(c);
}
Static Interface Method:
It is a static method which belongs to the interface only. We can
write implementation of this method in interface itself.
Static method can invoke only on interface class not on class.
Interface and implementing class , both can have static method with the same name without overriding each other.
It can be used as a utility method
Default Method:
It is a method with default keyword and class can override this method.
It can be invoked on interface as well as class.
We can override the default method in implementing class.
It can be used to provide common functionality in all implementing classes.
There is a link with detailed explanation. For detailed example: Default method vs static method in an interface in Java?
So I know that in Java when you have a static method you are supposed to call it with the format ClassName.method() rather than use the same structure as you would for instance methods, namely:
ClassName myObject = new ClassName();
myObject.method();
However, if you were to do it this way it would still be valid code and would work. Let's say I decide to do this where the method in question is static, and have the following setup:
public SuperClass {
public static int foo(int x) {
return x;
}
}
public SubClass extends SuperClass {
public static int foo(int x) { // Overriding foo() in SuperClass
return x + 1;
}
}
public MyDriver {
public static void main(String[] args) {
SuperClass myObject = new SubClass(); // Upcasting.
System.out.println(myObject.foo(5)); // This should polymorphically print 6
}
}
What prints out on the screen, however, is 5 rather than 6. Why?
Static methods apply only to the class they are defined in, and they cannot be overridden.
When you call myObject.foo(5), you are calling SuperClass.foo(5) in reality, because you declared myObject as a SuperClass, regardless of whether you instantiated it as one.
The proper way to call a static method is to call it directly from the class it is declared in, so if you wanted to call SubClass.foo(), you must call it from an explicitly declared SubClass instance (meaning no upcasting), or you need to call SubClass.foo() like so.
The simple answer is that calling static methods from instances evaluates to calling those same methods from the declared type with no instance rather than the instance type.
I am not certain of this, but I would not be surprised if when the code is compiled into byte-code, that the instance static method call would actually be compiled into a direct call to the declared type.
Edit: An upvote brought my attention back to this and I cleaned up the explanation to make it more clear and fix some negligible grammatical mistakes on my part. I hope this helps future readers.
Using instances of a class to call that class's static methods is something you should avoid, since it can cause confusion. If you need to call any method polymorphically, make it an instance method. You cannot polymorphically call a static method. The reason the SuperClass invocation is called is because that is the apparent class of myObject at compile-time. This effect can also be seen in the following scenario:
public void doSomething(SuperClass param) {
System.out.println("SuperClass");
}
public void doSomething(SubClass param) {
System.out.println("SubClass");
}
public void test() {
SuperClass myObject = new SubClass();
doSomething(myObject);
}
If test() is called, SuperClass will be printed.
Static methods don't depends on the instance, they belong to the class and only to the class, in fact if you have a static method you'll always access to one unique instance always.
myObject.foo(5)
is only a shortcut, what you really are doing is
SuperClass.foo(5)
Static methods are treated as global by the JVM, they are not bound to an object instance at all. By the way, you can only overload static methods, but you can not override. So check for "Oracle Documentation for Overriding and Hiding Documents".
Defining a Method with the Same Signature as a Superclass's Method:
-----------------------------------------Superclass Instance MethodSuperclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides
Sorry to bring back the dead. But I still don't clearly understand what this section of specification states.
If an interface has no direct superinterfaces, then the interface
implicitly declares a public abstract member method m with signature
s, return type r, and throws clause t corresponding to each public
instance method m with signature s, return type r, and throws clause t
declared in Object, unless a method with the same signature, same
return type, and a compatible throws clause is explicitly declared by
the interface. It is a compile-time error if the interface explicitly
declares such a method m in the case where m is declared to be final
in Object.
Given
interface Testing
{
void test();
}
public class Test{
public static void main(String[] args) {
Testing t = new Testing(){
#Override
public void test(){
}
};
t.test();
t.toString();
}
}
Now as the spec states that the above will change to
interface Testing
{
void test();
String toString();
//other non-final methods of Object
}
public class Test{
public static void main(String[] args) {
Testing t = new Testing(){
#Override
public void test(){
}
};
t.test();
t.toString();
}
}
Also. please confirm if there is an hierarchy of interfaces then all of them get these abstract methods.
What it means is that every class extends Object (at some point in its class heirarchy). However, interfaces do not extend Object. This is to avoid the problems that arise from multiple inheirtance.
Since interfaces do not extend Object that would mean we were unable to use methods like toString if the type (not class) of the object we had access to was an interface. But we know those methods must be available since all classes at some point extend from Object. Therefore, to get around this problem all of Object's not final methods are implicitly declared in all interfaces that have no superinterfaces. These contracts of these methods are always satisfied since all classes must at some point extend from Object.
TL;DR -- it's a trick to make sure we can access the methods made available by Object when we have an instance of some class stored in variable that's type is an interface (eg. Serializable)
edit: To answer your question, You're slightly off. All non-final methods of Object are added to an interface (whether they are used or not) if that interface has no parent interface AND for each method to added: that there is no matching method is explicitly declared by the interface.
As long as there is no super interface to an interface it gets the implicit declaration of the Object class methods. As long as these methods are included in the interface. Every interface that either extends or implements this interface doesn't see much difference between the methods that are explicitly declared by this interface or it got implicitly. That point forward that interface is as good as declared them explicitly.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can we override static method in Java?
We cannot override the static methods of the base class.
Actually I tried something like this:
// Base class
public class StaticExampleImpl {
protected String name="overriding";
public static void display(){
System.out.println("static method display : base class");
}
}
Then the derived class is as follows:
//derived class
public class StaticDemo extends StaticExampleImpl {
// cannot override the static methods...
//#Override
public static void display(){
System.out.println("child!!! static method display");
}
public static void main(String[] args) {
StaticDemo d=new StaticDemo();
d.display(); // derived class display is called rather than Base class.
}
}
So, when I uncomment the #Override method, it gives error as "Static methods cannot be overriden". But with commenting it works fine. So, when we create the Objects and call the static methods with the instances, those work fine. so what is the difference??
because static methods are not get inherited.
When you uncomment #Override it means you are trying to override the
static method which is not possible thats why you are getting an
error.
But when you comment //#Override it means you are declaring a new
method in child class.
Static methods does not belong to an instance of a class, it belongs to the actual class.
When you call d.display();, you are really calling the static method of the StaticDemo d reference's static method.
if you did :
StaticExampleImpl d2 = new StaticDemo();d2.display(), you will find that it calls the base class's display.
However, don't do this. It leads to confusing code, and is a bad way to implement inheritance poorly.
Overriding depends the an instance of a class. polymorphismis that you can subclass a class and the objects implementing those subclasses will have different behaviors for those method defined in the superclass (and overridden in the subclasses) .static methods does not belong to an instance of a class so the concept is not applicable.
Static methods cannot be inherited. If you want to call the 'base' class static method, you have to explicitely call StaticExampleImpl.display().
Static methods are bound to class they can't be inherited thats why you can't have base class static method in derived class.
If you are trying to override a static method, there is probably something wrong with your design.
OOP and Polymorphism allows you to do the following:
public class MyClass1 {
public String toString() { return "MyClass1 Instance"; }
}
public class MyClass2 extends MyClass1 {
#Override
public String toString() { return "MyClass1 Instance"; }
}
public void printSomething(MyClass1 myclass1){
System.out.println(myclass1);
}
Inside printSomething, the toString method which is going to be called is the one on the runtime type of myClass1: when you pass inside printSomething an instance of MyClass2, its compile-type will be MyClass1 but its runtime type will be MyClass2
It is clear that to use polymorphism you need objects instances, where the actual runtime type could different from the compile type. Static methods however do not belong to any object instance, but to the class. Why don't you explain us what you are trying to achieve?
The following code:
StaticExampleImpl one = new StaticExampleImpl();
StaticDemo two = new StaticDemo();
StaticExampleImpl three = two;
one.display();
two.display();
three.display();
Will yield the following output:
static method display : base class
child!!! static method display
static method display : base class
As you can see, the method does not get inherited. This is why they are called 'static methods': they are called statically, not dynamically, as instance methods would be. The compile-time type of the class is what matters when calling static methods, not the runtime type.
This is also why you shouldn't call static methods through object instances. Always call them like this:
StaticExampleImpl.display();
StaticDemo.display();
This completely takes away the confusion that might (will) come up when people expect inheritance to work for these methods.
any static block in java, may be static variables, methods are loaded when the class is loaded. You probably know about class loader in java. So thing is static block (methods, variables or anything is static) is loaded once. So you can’t actually override any static block.
Commenting #Override means that you are writing another static method in sub class, but not just overriding base class method.
Let's say I have a base class named Entity. In that class, I have a static method to retrieve the class name:
class Entity {
public static String getClass() {
return Entity.class.getClass();
}
}
Now I have another class extend that.
class User extends Entity {
}
I want to get the class name of User:
System.out.println(User.getClass());
My goal is to see "com.packagename.User" output to the console, but instead I'm going to end up with "com.packagename.Entity" since the Entity class is being referenced directly from the static method.
If this wasn't a static method, this could easily be solved by using the this keyword within the Entity class (i.e.: return this.class.getClass()). However, I need this method to remain static. Any suggestions on how to approach this?
Don't make the method static. The issue is that when you invoke getClass() you are calling the method in the super class - static methods are not inherited. In addition, you are basically name-shadowing Object.getClass(), which is confusing.
If you need to log the classname within the superclass, use
return this.getClass().getName();
This will return "Entity" when you have an Entity instance, "User" when you have a User instance, etc.
Not possible. Static methods are not runtime polymorphic in any way. It's absolutely impossible to distinguish these cases:
System.out.println(Entity.getClass());
System.out.println(User.getClass());
They compile to the same byte code (assuming that the method is defined in Entity).
Besides, how would you call this method in a way where it would make sense for it to be polymorphic?
This works for me
this.getClass().asSubclass(this.getClass())
But I'm not sure how it works though.
Your question is ambiguous but as far as I can tell you want to know the current class from a static method. The fact that classes inherit from each other is irrelevant but for the sake of the discussion I implemented it this way as well.
class Parent {
public static void printClass() {
System.out.println(Thread.currentThread().getStackTrace()[2].getClassName());
}
}
public class Test extends Parent {
public static void main(String[] args) {
printClass();
}
}
Create a member String variable in the superclass.
Add the this.getClass().getName() to a constructor that stores the value in the member String variable.
Create a getter to return the name.
Each time the extended class is instantiated, its name will be stored in the String and accessible with the getter.
The superclass should not even know of the existence of the subclass, much less perform operations based on the fully qualified name of the subclass. If you do need operations based on what the exact class is, and can't perform the necessary function by inheritance, you should do something along these lines:
public class MyClassUtil
{
public static String doWorkBasedOnClass(Class<?> clazz)
{
if(clazz == MyNormalClass.class)
{
// Stuff with MyNormalClass
// Will not work for subclasses of MyNormalClass
}
if(isSubclassOf(clazz, MyNormalSuperclass.class))
{
// Stuff with MyNormalSuperclass or any subclasses
}
// Similar code for interface implementations
}
private static boolean isSubclassOf(Class<?> subclass, Class<?> superclass)
{
if(subclass == superclass || superclass == Object.class) return true;
while(subclass != superclass && subclass != Object.class)
{
subclass = subclass.getSuperclass();
}
return false;
}
}
(Untested code)
This class doesn't know about its own subclasses, either, but rather uses the Class class to perform operations. Most likely, it'll still be tightly linked with implementations (generally a bad thing, or if not bad it's not especially good), but I think a structure like this is better than a superclass figuring out what all of its subclasses are.
Why do you want to implement your own getClass() method? You can just use
System.out.println(User.class);
Edit (to elaborate a bit): You want the method to be static. In that case you must call the method on the class whose class name you want, be it the sub-class or the super-class. Then instead of calling MyClass.getClass(), you can just call MyClass.class or MyClass.class.getName().
Also, you are creating a static method with the same signature as the Object.getClass() instance method, which won't compile.
A static method is associated with a class, not with a specific object.
Consider how this would work if there were multiple subclasses -- e.g., Administrator is also an Entity. How would your static Entity method, associated only with the Entity class, know which subclass you wanted?
You could:
Use the existing getClass() method.
Pass an argument to your static getClass() method, and call an instance method on that object.
Make your method non-static, and rename it.
If I understand your question correctly, I think the only way you can achieve what you want is to re-implement the static method in each subclass, for example:
class Entity {
public static String getMyClass() {
return Entity.class.getName();
}
}
class Derived extends Entity {
public static String getMyClass() {
return Derived.class.getName();
}
}
This will print package.Entity and package.Derived as you require. Messy but hey, if those are your constraints...
If i am taking it right you want to use your sub class in base class in static method
I think you can do this by passing a class parameter to the method
class Entity {
public static void useClass(Class c) {
System.out.println(c);
// to do code here
}
}
class User extends Entity {
}
class main{
public static void main(String[] args){
Entity.useClass(Entity.class);
}
}
My context: superclass Entity with subclasses for XML objects.
My solution:
Create a class variable in the superclass
Class<?> claz;
Then in the subclass I would set the variable of the superclass in the constructor
public class SubClass {
public SubClass() {
claz = this.getClass();
}
}
it is very simple done by
User.getClass().getSuperclass()