implementing a interface to a class: class to interface to interface - java

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?

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

public class A<T> { // am I supposed to have a class here? or just have the interface?
public interface A<T> extends B<T>
{
This is ambigous. Is A the interface or the class?
Only interfaces can be "implemented". You cannot implement a class.
So I guess your issue is done by changing those into:
File DoubleLinkedList.java:
public class Doublelinkedlist<T> implements A<T>
{
// ... blah blah
}
-> The class implements interface A
File A.java:
public interface A<T> extends B<T>
{
// ...
}
-> The interface extends interface B
File B.java:
public interface B<T> extends Iterable<T>
{
// ...
}
-> The interface extends interface Iterable

public interface Entity{
public int getId();
public void setId(int id);
public int getHealth();
public void setHealth(int health);
}
public class Tank implements Entity{
//without implementing the methods mentioned in Entity you will immediately see a red line //under "Tank" in your IDE saying un-implemented methods.
}
public class Tank implements Entity{
private int id;
private int health;
public Tank(){..}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public int getHealth(){
return health;
}
public void setHealth(int health){
this.health = health;
}
}
an interface is a contract between the class that is implementing the interface, it is saying "HEY YOU, you have signed up to use me, so you better take these methods and define them properly".
An interface will only describe method headers, but not actually offer any content to it, it is left to the class that implements the interface.
further more, understand the following
inheritence - enables a class to inherit the attributes and methods of its parent class, but the same child class cannot inherit directly from 2 parent classes, you can however have a child class inherit from a parent class which inherits from another class which implements an interface.
here is an example
public interface Entity{
...
}
public Soldier implements Entity{
// implements the entity interface,
//and defines the methods
}
public SwordsMan extends Soldiers{
//this class inherits the methods and attributes of soldier
//which had also implemented the methods from entity
}
You also mention trying to extend an interface into an interface, interfaces are designed with no implemented methods, if you want to use two interfaces you are best to do this:
public class Aircraft implements Engine, Entity{
//this class then has to implements all methods from Engine and Entity
}

Related

Does abstract Class enforce Implementing all abstract methods on the first level of inheritance,definitely?

If we have an abstract class called
public abstract class Person {
public abstract void Speak();
}
is it necessary to implement the abstract method if we try to inherit this class in EnglishPerson Class ? Why?
Does abstract Class enforce Implementing all abstract methods on the
first level of inheritance,definitely?
Not necessarily. If the first level of inheritance is an abstract class, it is not enforced to implement all abstract methods from its hierarchy.
Base class (abstract):
public abstract class Person {
public abstract void speak();
}
Child class (abstract):
public abstract class EnglishPerson extends Person {
}
Child of the Child class (first concrete class):
public class ConcreteEnglishPerson extends EnglishPerson {
public void speak(){
// your impl
}
}
As you see, the ConcreteEnglishPerson class is concrete. So, now, you have not the choice : you cannot have any abstract methods from the hierarchy that is not implemented.
Looks like the original question has changed since I posted my answer, so I'll update my answer to match it..
An abstract class ONLY requires implementation of all members if the inheriting class is NOT abstract. If the inheriting class IS abstract, you do not have to implement the parent classes methods.

Accessing a Class which extends an AbstractClass which itself extends another Abstract Class

I had a number of classes which extended an abstract class. Each of these classes could be returned in a 'set' by a method elsewhere in the project.
public abstract class AbstractBuilding{
....
}
public class ABuilding extends AbstractBuilding{
....
}
In another class:
World world = worldManager.getWorld();
for (AbstractBuilding building : world.getBuildings()){
if (building.toString().contains("SomeSequence")){
//Do Something
}
}
Where world.getBuildings() returns a set of all Abstract Buildings/classes.
Due to design changes, ABuilding is now an Abstract Class itself in addition to extending the original AbstractBuilding. And more classes extend from ABuilding.
Note: I still have other regular classes which extend AbstractBuilding as before - ABuilding2
public abstract class AbstractBuilding{
....
}
public class ABuilding2 extends AbstractBuilding{
....
}
public abstract class ABuilding extends AbstractBuilding{
....
}
public class TheBuilding extends ABuilding{
....
}
When I call the world.getBuildings method now, I still get the set of all abstract buildings, which include buildings such as TheBuilding as it extends ABuilding which itself extends AbstractBuilding.
Is there some way that I can identify if a building in the returned set of buildings extends from this new abstract building?

Java interface not enforced

I have the following class definition:
public class SyrianEdge extends BaseEdge<SyrianVertex, SyrianEdge>
implements Weighted, Blockable{
...
}
And the interface:
public interface Weighted{
public long getWeight();
}
The class SyrianEdge doesn't have the method public long getWeight() but everything seems to compile fine.
What am I missing? How come the interface doesn't force the class to have its methods?
If you look at this basic example :
interface Weighted{
public long getWeight();
}
abstract class Parent implements Weighted {
#Override
public long getWeight() {
return 0;
}
}
class Child extends Parent {}
Since the Parent class already implements this method, there is no obligations for the Child class to implement it.
since you are extending BaseEdge, one can safely assume that BaseEdge implements Weighted and implemented the method getWeight().
if any one of the class in the inheritance tree implements an interface I then using the implement I on any class down the tree would produce no errors as it has been already implemented (except the case in which all the classes up the tree are abstract s the first concrete class should implement all the methods declared in the Interface I).

Interface > Abstract Class > Concrete Class pattern

I have found a reference architecture where all domain classes (POJOs) inherit an abstract class and, in turn, the abstract class implements a interface. For instance:
public interface User {
public abstract operation1();
public abstract operation2();
...
}
public abstract class AbstractUser implements User {
String name;
// only attributes
...
}
public abstract class XyzUser extends AbstractUser {
...
}
Do you guys know if this design is some sort of pattern? Can you explain why the architecture was designed like that (Interface --> Abstract Class --> Concrete Class)?
First understand what is need of interface, abstract class and concrete class.
Let us take example here:
public interface Vehicle{
public void startEngine();
public void run();
}
public abstract class Bus implements Vehicle{
public void startEngine(){
System.out.println("Engine Starting of bus");
}
}
public abstract class Plane implements Vehicle{
public void startEngine(){
System.out.println("Engine Starting of plane");
}
}
public class VolvoBus extends Bus{
public void run(){
System.out.println("Running at 100kmp/h");
}
}
public class NonACBus extends Bus{
public void run(){
System.out.println("Running at 50kmp/h");
}
}
public class Test{
public static void main(String[] args){
VolvoBus volvoBus=new VolvoBus();
NonACBus nonAcbus=new NonACBus();
volvoBus.startEngine();
volvoBus.run();
nonAcBus.startEngine();
nonAcBus.run();
}
}
See in above example we have code which is common for bus whether its AC bus or Volvo so it is written in Bus class but run() is not common for all so instead of implementing in Bus class it is kept as abstract so its child class will implement that base on there requirement.
My code will explain you better :)
Thanks
Here the interface User defines a type:
public interface User{
public abstract operation1();
public abstract operation2();
...
}
So implementations of this interface are to be known as of type User.
Now you can provide implementation assistance to the implementers of this interface by using Abstract classes, as interfaces are not permitted to have method implementations. You can provide a skeletal implementation class to go with User interface, which will have default implementations of some of its methods. Here AbstractUser is the skeletal implementation of User:
public abstract class AbstractUser extends IUser
{
public abstract operation1();
public operation2(){
...
}
}
You can now write concrete User implementations with the help of AbstractUser:
public class UserImpl extends AbstractUser implements User {
...
}
The Java Collections Framework has a number of skeletal implementation to go along with the main collection interfaces, to minimize the effort required to implement the collection interfaces: AbstractSet, AbstractList, etc.
When designing code that is meant to be extended, it is standard practice to rely only on interfaces. To make life easier to extenders, boilerplate code is added to abstract classes extending those interfaces.
This is standard OO practice, rather than a "pattern". A good example can be found in just about all Java Swing widget models. For example TableModel is an interface meant to provide access to a table's data, AbstractTableModel is an abstract class that provides implementations for some simple accounting methods in the interface, and DefaultTableModel is a concrete class that uses, as data storage, an ArrayList.
This might be the decorator design pattern. U have an interface, an abstract class that implements the interface. Concrete classes extending the abstract class (decorators). and another concrete class that only implements the interface (the object which you decorate). I am not sure. I cannot tell anything without looking at the entire code. But still, have a look at this link. It might help you.
http://javapapers.com/design-patterns/decorator-pattern/
I have had this kind of architecture implementation. For example here is snippet of code
public class Category extends CategoryBase implements ICategory
Another is
public class Functional extends CategoryBase implements ICategory
Here interesting thing is CategoryBase abstract class where You are keeping your common properties and functionalities and You are just reusing them with inheritance
Abstract class is a generalized class for example animal is generalized because abstract method and properties are mentioned here. As many animal has common behaviors and properties.
Concrete Class is a specilized class for a dog which is inherited from animal class (generalized class) to do more specilized for dog only. here we can add some properties and method and even override it's behaviour (from generlized class)
Interface is a task based class which have only abstract methods which can be implemented in abstract class or/and in concrete class to specilized behaviours
Example code here...
abstract class Animal {
private String leg;
abstract void run();
}
class Dog extends Animal implements Ibehaviors {
#Override
void run() {
System.out.println("dog run");
}
#Override
void eat() {
System.out.println("dog eat");
}
}
interface Ibehaviors {
void eat();
}

How to create an object of an abstract class and interface

How do I create an object of an abstract class and interface? I know we can't instantiate an object of an abstract class directly.
You can not instantiate an abstract class or an interface - you can instantiate one of their subclasses/implementers.
Examples of such a thing are typical in the use of Java Collections.
List<String> stringList = new ArrayList<String>();
You are using the interface type List<T> as the type, but the instance itself is an ArrayList<T>.
To create object of an abstract class just use new just like creating objects of other non abstract classes with just one small difference, as follows:
package com.my.test;
public abstract class MyAbstractClass {
private String name;
public MyAbstractClass(String name)
{
this.name = name;
}
public String getName(){
return this.name;
}
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyAbstractClass ABC = new MyAbstractClass("name") {
};
System.out.println(ABC.getName());
}
}
In the same way You can create an object of interface type, just as follows:
package com.my.test;
public interface MyInterface {
void doSome();
public abstract void go();
}
package com.my.test;
public class MyTestClass {
public static void main(String [] args)
{
MyInterface myInterface = new MyInterface() {
#Override
public void go() {
System.out.println("Go ...");
}
#Override
public void doSome() {
System.out.println("Do ...");
}
};
myInterface.doSome();
myInterface.go();
}
}
There are two ways you can achieve this.
1) Either you extend / implement the Abstract class / interface in a new class, create the object of this new class and then use this object as per your need.
2) The Compiler allows you to create anonymous objects of the interfaces in your code.
For eg. ( new Runnable() { ... } );
Hope this helps.
Regards,
Mahendra Liya.
You can provide an implementation as an anonymous class:
new SomeInterface() {
public void foo(){
// an implementation of an interface method
}
};
Likewise, an anonymous class can extend a parent class instead of implementing an interface (but it can't do both).
public abstract class Foo { public abstract void foo(); }
public interface Bar { public void bar(); }
public class Winner extends Foo implements Bar {
#Override public void foo() { }
#Override public void bar() { }
}
new Winner(); // OK
"instantiate" means "create an object of".
So you can't create one directly.
The purpose of interfaces and abstract classes is to describe the behaviour of some concrete class that implements the interface or extends the abstract class.
A class that implements an interface can be used by other code that only knows about the interface, which helps you to separate responsibilities, and be clear about what you want from the object. (The calling code will only know that the object can do anything specified in the interface; it will not know about any other methods it has.)
If you are using someone else's code that expects a Fooable (where that is the name of some interface), you are not really being asked for an object of some Fooable class (because there isn't really such a class). You are only being asked for an instance of some class that implements Fooable, i.e. which declares that it can do all the things in that interface. In short, something that "can be Foo'd".
You write a class that derives from the abstract class or implements the interface, and then instantiate that.
What you know is correct. You cannot create an object of abstract class or interface since they are incomplete class (interface is not even considered as a class.)
What you can do is to implement a subclass of abstract class which, of course, must not be abstract. For interface, you must create a class which implement the interface and implement bodies of interface methods.
Here are orginal tutorial on oracle site, http://download.oracle.com/javase/tutorial/java/IandI/abstract.html and http://download.oracle.com/javase/tutorial/java/concepts/interface.html
You can not instantiate the abstract class or an interface, but you can instantiate one of their subclasses/implementers.
You can't instantiate an abstract class or an interface, you can only instantiate one of their derived classes.
In your example
MyAbstractClass ABC = new MyAbstractClass("name") {
};
You are instantiating any class that implements Suprising.
public abstract class AbstractClass { ... }
public interface InterfaceClass { ... }
// This is the concrete class that extends the abstract class above and
// implements the interface above. You will have to make sure that you implement
// any abstract methods from the AbstractClass and implement all method definitions
// from the InterfaceClass
public class Foo extends AbstractClass implements InterfaceClass { ... }
NO, we can't create object out of an interface or Abstract class because
Main intention of creating an object is to utilize the wrapped methods and data.
As interface don't have any concrete implementation hence we cannot.
For abstract class we may have concrete method or abstract method or both.
There is no way for the API developer to restrict the use of the method thats don't have implementation.
Hope help.
No, you are not creating the instance of your abstract class here. Rather you are creating an instance of an anonymous subclass of your abstract class. And then you are invoking the method on your abstract class reference pointing to subclass object.

Categories

Resources