Java static method inheritance

Java static methods and interfaces/inheritance

At the moment, I made that method non static. Also, ideally, that shouldn’t involve having a second hierarchy of classes that must be kept in sync just for that one method. Many Thanks ====== EDIT: People asked for an example so here you go: OK, let’s say i have a hierarchy of animal classes (abstract Animal class > abstract Mammal class > Cat class, Dog class, Dolphin class, etc). I want to know if I put this interface in class all of these classes have access to it.

Java static methods and interfaces/inheritance

Ok, so I have a hierarchy of classes and subclasses. They all must have certain methods. Those methods are in an interface implemented by the superclass and everything below.

There is one method they should all have and define but that method is «in spirit», of the static kind, returning the same results for all instances of a given class.

Unfortunately, one cannot have a static method as part of an interface and also, static method do not support inheritance, they «hide» rather than «override».

So, what are the options for a static method that all classes in a hierarchy must have and that can be called in a generic way? At the moment, I made that method non static.

Also, ideally, that shouldn’t involve having a second hierarchy of classes that must be kept in sync just for that one method.

EDIT: People asked for an example so here you go:

OK, let’s say i have a hierarchy of animal classes (abstract Animal class > abstract Mammal class > Cat class, Dog class, Dolphin class, etc). Some of the behaviour will be instance specific, they may have members like «weight», «name», «age», etc and have related getter/setter.

but then, there might be one method that would typically give the same result for all the instances of a given class, for example it could be one of those:

-int getNumberOfLegs(); -String getFavouriteFood(); 

All cats have 4 legs so that method could be static, it’s not instance-dependant. it’s more like meta information. I want to be able to do Cat.getNumberOfLegs(). I want to force the existence of that method on all my hierarchy in a way that can be overridden, etc.

Though it shall be better if you can support your question with example. From what I understood is, you want subclasses to write their own behavior for certain method — thus you need overriding. Thus probably this method is not a candidate for being static. Probably what best you can do is, to have an abstract class. Provide a default implementation, if you really insist. Or Just make sure that every subclass defines it. For that make the method it self as abstract.

I want to force the existence of that method on all my hierarchy in a way that can be overridden, etc.

Above is clearly indication that you need abstract. Not Static.

-int getNumberOfLegs(); -String getFavouriteFood(); 

Shall be different for dolphin and dog. So there is no way you can do it through static method. Static method can be for your mammel class where it can have something like

Static has to be class level. But since you want the same interface to access instance specific information, you shall have to use abstract (for forcing each implementation to have it).

Читайте также:  Доклад про язык html

Apart of an abstract method in your Animal that would be overriden in each class to provide a constant value like

you can also create non-abstract method in your superclass and provide the constant through super constructor like this:

class Animal < private final int numberOfLegs; protected Animal(int numberOfLegs) < this.numberOfLegs = numberOfLegs; >public final int getNumberOfLegs() < return numberOfLegs; >> class Cat extends Animal < private static final int NUMBER_OF_LEGS_ON_A_CAT = 4; public Cat() < super(NUMBER_OF_LEGS_ON_A_CAT); >> 

This approach may be less verbose, on the other hand can become quite unreadable if there’s too many constants like this.

The bottom line is however that static methods and subtyping don’t go well together, so the best you can do is probably make the method non-static and ensure that the data it returns is static — this is achieved by providing a constant through constructor into a final field, by returning a constant in the overriden method, etc.

Are static methods inherited in Java?, Static methods in Java are inherited, but can not be overridden. If you declare the same method in a subclass, you hide the superclass method instead of overriding it. Static methods are not polymorphic. At the compile time, the static method will be statically linked. Example: Code sampleclass A >Feedback

Static method inherit in java

Suppose I have a POJO User ,which I add some static method to do the CRUD operation:

public class User < private String name; private int age; // getter and setter omitted // public static void add(User user) < // add person >public static int delete(Object id) < // delete person return 1; >> 

Since I have other entities like User,so I want to make the add and delete method abstracted,something like this;

public class?interface Entity < static add(T t); static delete(Object id); >public class User extends Entity < @override static add(User user)< // add . >. > 

First you can’t define static methods in interface. See this discussion

Second, You can’t override static methods. See this discussion.

I am not sure about your requirement, if applicable, I would suggest leave them as instance methods and allow each class to provide it’s own implementation (as Bohemian suggested).

Don’t make the CRUD methods static in the entity classes, create a generic DAO interface instead and then implement concrete DAO class for each entity type.

Don’t use static methods for such scenario. A better and more OOP approach is to use a Dependency Injection framework that creates only one instance of each concrete DAO class to save memory and time (for creating new DAO instances again and again) and reuses those instances in all places in your application that need to access them.

public interface Dao  < // you can customise these signatures by your needs // these are just my suggestions T get(long id); ListgetAll(); T add(T t); T update(T t); void delete(T t); > public class UserDao implements Dao  < public User get(long id) < . >public List getAll() < . >public User add(User user) < . >public User update(User user) < . >public void delete(User user) < . >> 

You can’t override static methods, but there is no good reason why these methods should be static. Make them instance methods:

The interface should look like:

public void add() < // add "this" >public int delete() < // delete "this" return 1; >

This code pattern is very common — I’ve seen it many times — and it works well.

Читайте также:  Решение задачи питон соседи одного знака

If you don’t want to use instance methods, you can create static methods in a utility class to deal with such objects:

public class DaoUtil < public static void add(Entity entity) < // some impl >public static int delete(Class clazz, T id) < // some impl >> 

Java static methods and interfaces/inheritance, Unfortunately, one cannot have a static method as part of an interface and also, static method do not support inheritance, they «hide» rather than «override». So, what are the options for a static method that all classes in a hierarchy must have and that can be called in a generic way? At the moment, I …

Java, Is it possible to inherit interface?

In my application I have a class, let me call it class A . Four classes, let me call them B , C , D and E extend from this class. Each of these four classes has an interface that its functionality is same.

I want to know if I put this interface in class A all of these classes have access to it. Am I right?

I have another class, G that is implementing this interface. If I implement this interface does it apply to those four libraries at same time?

Update Let me go into detail. I have four classes. Each class has a method that when this class connects to internet will set a flag. like this.

public class ClassB extends < public interface OnConnectingToServer < public void onGettingDataFromServer(boolean flag); >public ClassB () < if(I'm_downloading_from_internet) OnConnectingToServer.onGettingDataFromServer(true); >> 

I have this situation for «B», «C», «D» and «E» classes. Class «G», implements this interface. If I want to put each interface in each class therefore, i need to assign four different names ans in «G» class also implements 4 interfaces. I think this way is not a good way.

I’m looking for a way that instead of implementing 4 same interfaces, implementing just one interface. therefore, regardless of triggering the interface by one class or all four classes, just one implementation is done.

Hope to make it more clear. Thanks again.

Don’t put the interface definition inside class A. Make it a separate top-level type and then make all your classes implements MyInterface . If class B extends A , then you don’t have to explicitly say implements MyInterface since there is no way for a subclass to «unimplement» an interface.

  • Yes, if you let A implement an interface, then all classes that extend that class also implement that interface.
  • Not entirely sure what you mean with letting G implement the interface. Doing that will only affect classes that extend G .

A class may be declared to directly implement one or more interfaces, meaning that any instance of the class implements all the abstract methods specified by the interface or interfaces. A class necessarily implements all the interfaces that its direct superclasses and direct superinterfaces do . This (multiple) interface inheritance allows objects to support ( multiple) common behaviors without sharing any implementation.

If you implement the interface (call it I) in class A and B, C + D extend A then B, C and D will implement the I interface as well.

This means you will be able to write:

I aInstance = new A(); I bInstance = new B(); 
A aInstance = new A(); A bInstance = new B(): 

because logically your data model will become:

A is an I and B is an A so this implies: B is an I 

If class G implements the interface but doesn’t inherit A you will have to implement the functionality defined in I in the class G as well.

This means you will be able to write:

I aInstance = new A(); I gInstance = new G(); 

but not this (this won’t compile): A gInstance = new G();

Just remember, the interface is only a contract. Any class that implements an interface is bound to respect the contract but no implementation is inherited (no implementation can exist in the interface anyway).

Inheritance of Interface in Java with Examples, The following is an example which implements the multiple inheritances in interfaces: The result is : 15.0 The result is : 20.0 The result is : 54.0 The result is : 7.5. Superinterface-Subinterface relationship: A subinterface type reference variable can be assigned to super interface type reference variable.

Источник

Are static methods inherited?

I have seen many people arguing that static methods are not inherited. That is one misconception many beginning programmers have. According to true object oriented principles, static methods should not have inherited, but with Java a class does inherit all members of parent class including static.

So what is the answer to the question of if static methods are inherited? A simple answer as per Java Language Specification would be «Yes» for classes and «No» for interfaces:

  • The Java Language Specification 8, section 8.4.8, titled as ‘Inheritance, Overriding, and Hiding’ says that «A class C inherits from its direct superclass all concrete methods m (both static and instance). » and «A class C inherits from its direct superclass and direct superinterfaces all abstract and default methods. «.
  • The above section also say that this rule of inheritance for static methods does not apply for interfaces, as the specification also says «A class does not inherit static methods from its superinterfaces».

There are more constraints to these rules and for more details, please refer to the section mentioned above in the Java Language Specification 8.

So why people get fooled easily?

First, they refer to everything other than the official Java Language specification.

Also, there is a difference in the way these are treated when redefined in a subclass. Or to be more precise, only instance methods can be overriden. Instance variables, static variables and static methods are treated the same, and are not overriden in a subclass and the process is called as hiding.

You may try using the @Override annotation to see if an override is valid, over an instance method, static method, instance variable and static variable. You will be only allowed to place them over an instance method.

So what do you mean by overriding?

When you assign a child object to a parent reference, the actual member selected at run time for an overriden member will depend on the actual object used at runtime.

For non-overriden members like instance variables, static variables and static methods, the member selected will not depend on the actual object at runtime.

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass. The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass. For a better clarity on overriding and hiding, please read the official Oracle notes that also give you some examples @ http://docs.oracle.com/javase/tutorial/java/IandI/override.html.

Yes, there is some confusion and hence many text books say it differently. All that matters is understanding how it works.

Источник

Оцените статью