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).
Related
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.
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?
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();
}
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
}
I came to situation :
public interface Intr {
public void m1();
}
public abstract class Abs {
public void m1() {
System.out.println("Abs.m1()");
}
// public abstract void m1();
}
public class A extends Abs implements Intr {
#Override
public void m1() {
// which method am I overriding, well it is Abs.m1() but why?
// if method implemented is Abs.m1(), then why I am not getting error for Intr.m1() not implemented.
}
}
You are satisfying both conditions at once; ie. the one implementation is at the same time fulfilling the abstract class requirements and the interface requirements.
As a note, unless you are using Intr in another inheritance chain, you don't need it. Also, it might make sense to move the implements Intr up to the abstract class definition.
You can only override methods defined in another class.
Methods declared in an interface are merely implemented. This distinction exists in Java to tackle the problem of multiple inheritance. A class can only extend one parent class, therefore any calls to super will be resolved without ambiguity. Classes however can implement several interfaces, which can all declare the same method. It's best to think of interfaces as a list of "must have"s: to qualify as a Comparable your cluss must have a compareTo() method but it doesn't matter where it came from or what other interfaces require that same method.
So technically you override Abs.m1() and implement Intr.m1() in one fell swoop.
Note that this would be fine too:
public class B extends Abs implements Intr {
//m1() is inherited from Abs, so there's no need to override it to satisfy the interface
}
Here, both the interface and abstract class have the same method.
You have one class with named Derived which extends an abstract class and implement an interface. It's true and you override print method on Derived class it's fine and it compiles correctly and does not give any error but here you can't identify which class method is overridden like abstract class or interface.
This is runtime polymorphism you can't create an instance of an abstract class or interface but you can create a reference variable of that type. Here the solution is you can't identify that on compile-time it's actually overridden at run time.
interface AnInterface
{
public void print();
}
abstract class Base
{
public abstract void print();
}
public class Derived extends Base implements AnInterface
{
public void print(){
System.out.println("hello");
}
AnInterface iRef = new Derived();
iRef.print(); // It means interface method is overridden and it's decided when we call the method.
Base base = new Derived();
base.print(); // It means abstract class method is overridden.
}
#Override ensures you override the method with no difference Interface or abstract superclass. So no error with override.
On the other hand Interface method is also implemented in the superclass which is enough for Interface contracts.