Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implementing a interface to a class: class to interface to interface

Tags:

java

interface

hi im a beginner in this and im trying to implement a class to a interface. The interface extends another interface. Im making a class with methods to run through a list and interfer with it, the two interfaces are apart of this.

The two interfaces are in each its separate file, but everything is in the same package, hope this is right.

Im getting the following errors:

From the class doublelinkedlist: interface expected here

From the interface A: doublelinkedlist.A is already defined in doublelinkedlist, interface expected here

From interface B: doublelinkedlist.B is already defined in doublelinkedlist

Code class:

package doublelinkedlist;

import java.util.*;

public class Doublelinkedlist<T> implements A<T>
{

Code interface A: (in separate file called A.java )

package doublelinkedlist;

import java.util.Iterator;


public class A<T> { // am I supposed to have a class here? or just have the interface?

  public interface A<T> extends B<T> 
  {

Code interface B: (in separate file called B.java )

package doublelinkedlist;

public class B<T> {

  public interface B<T> extends Iterable<T> 
  {

There is no code for the two interfaces in the class, so I dont understand why i get an error saying its already defined. Anybody got a clue?

like image 602
comodeque Avatar asked Oct 15 '13 14:10

comodeque


1 Answers

interface expected here indicates that the compiler is expecting an interface after implements, where you have given it a class (since the declaration for class A<T> came first).

doublelinkedlist.A is already defined in doublelinkedlist, interface expected here is thrown because you have a class named A and an interface inside the class named A, they can't both have the same name (same with B)

While you can technically have an interface inside of a class, that's not really the best design (since interfaces were intended to abstract, or hide, away the details of the underlying classes, they are typically more visible), so try to avoid doing that unless you have a good reason :)

This is probably what you're looking for:

Doublelinkedlist.java:

package doublelinkedlist;

import java.util.*;

public class Doublelinkedlist<T> implements A<T>
{...}

A.java:

package doublelinkedlist;

import java.util.Iterator;

public interface A<T> extends B<T> 
{...}

B.java:

package doublelinkedlist;

public interface B<T> extends Iterable<T> 
{...}

Further reading on interfaces: http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html

like image 141
Klazen108 Avatar answered Sep 20 '22 01:09

Klazen108