Java interfaces without methods

Interfaces without methods vs fields

As OOP point of view, you would use abstract class, but with Java refusing diamond relation, you will need to do some choice to defined the most logic inherited structure and add the rest use a relation probably. In Java 8, you can add default implementation in interface, not perfect but can do the trick for some case (carefull to that usage too)

@YthioCsi It looks as if the subject matches my question, but the problem is that by using this paradigm, Animal class will have tons of fields (since I need fields instead of methods), and hence each inheriting class will hold all of these fields, which brings me back to the most naive implementation. Perhaps a better idea would be to have the Animal class almost naked, and creating an inheriting class for each possible category, and then using multiple inheritance ?

First let’s organize info by grouping related categories like Flying, Walking, Swimming together in a group and Carnivore, Vegetarian into another group. Since every group can hold only specific correct set of values this means they are actually Enums. So we will have MovementType Enum and FoodType Enum. Therefore you can use these enums simply for properties in Animal class.

1 Answer 1

The pattern that you seem to describe is that of a trait or perhaps a mixin.

Mixins are a language concept that allows a programmer to inject some code into a class. Mixin programming is a style of software development, in which units of functionality are created in a class and then mixed in with other classes.

In Java 8, with the help of default methods, we can do traits to some extend, and I say so, because that is not the reason why default methods were designed.

Now, it is hard to suggest ideas on your design without having full details of what you’re doing, but I’ll try to give an example of how I see it from my perspective.

Let’s focus on eating profiles: carnivores vs herbivores. Carnivores eat other animals, herbivores eat plants or things of vegetal origin and omnivores may eat both. Both animals and plants are edible materials.

interface Edible < CollectiongetNutrients(); > interface Vegetal extends Edible <> interface Animal extends Edible<> 

All animals eat, so we could define animal as:

interface Animal extends Edible < Stomach getStomach(); Collectionmasticate(T food); default void eat(T food) < Objects.requiresNonNull(food, "The food must not be null"); for(Bolus bolus : this.masticate(food)) < this.getStomach().ingest(bolus); >> > 

Spare me the details of Stomach and Bolus , and let’s just assume all animals have a stomach and a way to masticate the food, turn it into a bolus and ingest it into their stomachs.

Now, we can finally reach our definition of:

interface Carnivore extends Animal < >interface Herbivore extends Animal < >interface Omnivore extends Animal

class Chicken implements Herbivore <> class Lion implements Carnivore <> class Bear implements Omnivore <> 

Now a Chicken can only eat things of Vegetal type, and Lion only things of Animal type, whereas Bear can eat any Edible thing.

Читайте также:  Exit and die in php

The more details I put on the default methods of my interface Animal, the less details I will need to implement in these classes and tha’ts, perhaps, a way to accomplish what you want.

I am aware that I may have not been able to answer your question, but I hope I have at least given you some ideas of where you can continue your investigation and experimentation of the ideal solution.

Источник

Can we write an interface without any methods in java?

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces.

A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.

Example

Consider the following example, here we have class with name Student which implements the marking interface Cloneable. In the main method we are trying to create an object of the Student class and clone it using the clone() method.

import java.util.Scanner; public class Student implements Cloneable < int age; String name; public Student (String name, int age)< this.age = age; this.name = name; >public void display() < System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); >public static void main (String args[]) throws CloneNotSupportedException < Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); int age = sc.nextInt(); Student obj = new Student(name, age); Student obj2 = (Student) obj.clone(); obj2.display(); >>

Output

Enter your name: Krishna Enter your age: 29 Name of the student is: Krishna Age of the student is: 29

In this case the cloneable interface does not have any members, you need to implement this just to mark or tag the class indicating that its objects are cloneable. If we do not implement this interface you cannot use the clone method of the Object class.

If you Still try, it throws a java.lang.CloneNotSupportedException exception.

Example

In the following Java program, we are trying to use the clone() method of the Object class without implementing the Cloneable interface.

import java.util.Scanner; public class Student < int age; String name; public Student (String name, int age)< this.age = age; this.name = name; >public void display() < System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); >public static void main (String args[]) throws CloneNotSupportedException < Student obj = new Student("Krishna", 29); Student obj2 = (Student) obj.clone(); obj2.display(); >>

Run time Exception

This program gets compiled successfully but, while executing it raises a runtime exception as −

Output

Exception in thread "main" java.lang.CloneNotSupportedException: Student at java.base/java.lang.Object.clone(Native Method) at Student.main(Student.java:15)

Источник

Adding methods or not adding methods to interface?

In Java 8, we can have default implementations for methods in interfaces, in addition to declarations which need to be implemented in the concrete classes. Is it a good design or best practice to have default methods in an interface, or did Java 8 come-up with that only to provide more support on older APIs? Should we start with using default methods in new Java 8 projects? Please help me to understand what is good design here, in detail.

Читайте также:  Python vk api timeout

Are you speaking of the term default implementation of a method? There is no other possibility to add content to a method in interfaces.

tutorialspoint.com/java8/java8_default_methods.htm . upvoted because I could not find a duplicate on SO.

IMHO using default methods regularly must be avoided as for good practice, and can make debugging a bit tough, and if you really want to archive that you can go with abstract classes as they provide same functionality

3 Answers 3

Prior java8, you were looking towards versioned capabilities when talking about «reasonable» ways of extending interfaces:

interface Capability . interface AppleDealer < ListgetApples(); > 

and in order to retrieve an AppleDealer, there is some central service like

public T getCapability (Class type); 

So your client code would be doing:

AppleDealer dealer = service.getCapability(AppleDealer.class); 

When the need for another method comes up, you go:

interface AppleDealerV2 extends AppleDealer < . 

And clients that want V2, just do a getCapability(AppleDealerV2.class) call. Those that don't care don't have to modify their code!

Please note: of course, this only works for extending interfaces. You can't use this approach neither to change signatures nor to remove methods in existing interfaces.

Thus: just adding a new method to an interface; and having default to implement that method right there; without breaking any existing client code is a huge step forward!

Meaning: why wouldn't you use default methods on existing interfaces? Existing code will not care. It doesn't know about the new defaulted methods.

Default method in Interface has some limitations. You can not have data variables in Interface. In general the reason default methods were added for the following reason. Say in your previous version you wrote a class that implements an interface "A".In your next version you decided that it would be good idea to add a method to your interface "A". But you can not do so since any class that implements "A" now will not have that extra method and thus will not compile. This would be a MAJOR backwards compatibility breakdown. So in Java 8 you can add a default method implementation into interface so all classes that implemented old version of "A" will not be broken but will fall back on default implementation. So use this feature sparingly, only if indeed you need to expand your existing interface.

In earlier java versions it wasnt possible beacuase you had abstract classes to use concrete and declared methods only but. Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interface. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.

Let consider small example to understand how it works:

public interface oldInterface < public void existingMethod(); default public void newDefaultMethod() < System.out.println("New default method" " is added in interface"); >> 

The following class will compile successfully in Java JDK 8

public class oldInterfaceImpl implements oldInterface < public void existingMethod() < // existing implementation is here… >> 

Why Defaut Method? Reengineering an existing JDK framework is always very complex. Modify one interface in JDK framework breaks all classes that extends the interface which means that adding any new method could break millions of lines of code. Therefore, default methods have introduced as a mechanism to extending interfaces in a backward compatible way.

Читайте также:  Семантическая разметка в HTML5

However we can achive this backward compatability.but its always recommended to use interfaces with delarations only that is what they are best used for.

For simple example if You have an interface Human_behaviour you can utilize all the actions of this interface like to_Walk(); to_Eat() , to_Love() , to_Fight() say for example in every implementing class in a unique way for every human object.Like

One Human can Fight using Swords and another Object using guns and so forth. Thus Interface is a blessing but may always be used as per the need.

Источник

Is it possible to have an interface without a method in java

I am new to java and trying to understand interface.Making an interface without a method gives compile time error.What is the reason for this behaviour?

import java.io.*; interface A < int x=10; >class B implements A < System.out.print("i am in B and x is"+x); >class InterfaceEx < public static void main(String[] args) < A a; a=new B(); >> 

Interfaces don't need to have any methods or fields. What they have is up to you. just no implementation. post the error and we can help

5 Answers 5

Yes, it's possible to have an interface without a method in Java. In fact, the Serializable and Cloneable interfaces are built-in to Java and don't have any methods. They are called "marker" interfaces.

Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class.

As for why your B interface doesn't compile (now that you've supplied the code), you need to place your statement inside a method or constructor, such as:

Yes. java.io.Serializable interface is the example of such marker interface

+1 Clonable too. Any interface that was implemented as the marker design pattern will fit the description 😉

According to the java Language Specification

The body of an interface may declare members of the interface, that is, fields (§9.3), methods (§9.4), classes (§9.5), and interfaces (§9.5).

It does not say you have to so yes you can have empty interfaces

And from the above answer there are empty interfaces

This is not legal syntax. A class definition can only have variables or methods; that's it. That code out there by itself isn't a definition of a variable or a method, so the compiler doesn't know what to make of it.

If you define a method, then that method can have any instructions inside it.

You don't seem to understand what a class is, its a pretty fundamental concept to OOP and Java, although can be confusing at first.

Also, pay attention to your errors. One error is very different from another. You assumed that this error was due to an empty interface; that was wrong. It was a syntax error. If you'd read the compiler output, it would have told you this already. It tries to help you.

Источник

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