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();
}
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.
We can achieve the same functionality as interfaces by using abstract classes, So why java doesn't allow the following code?
abstract class Animals
{
public abstract void run();
}
abstract class Animals1
{
public abstract void run1();
}
class Dog extends Animals,Animals1
{
public void run() {System.out.println("Run method");}
public void run1() {System.out.println("Run1 method");}
}
I know that multiple inheritance can be achieved by using only interfaces but the above code does the same thing as the interfaces would have done it.
This is not allowed because you can do more than this with abstract classes. It wouldn't make sense to allow multiple inheritance, provided you only used an abstract class when you could have used an interface.
It is simpler to only use abstract classes for things you can't do with an interface, in which case you wouldn't be able to use two abstract parent classes.
Note: with Java 8 there is less you can't do with an interface, you can have public instance and static methods with implementations.
In Java 9 you will be able to have private methods in interfaces ;)
This is because abstract classes are still classes, and inheritance is different than implementing an interface. Please see the differences between abstract class and interface. Also please see differences between inplementing an interface and extending a class in Java.
This both questions covers all the information you need to know to understand why you can't have multiple inheritance of abstract classes.
Also let me give you an example why this should not be allowed: Suppose you have the both Animals and Animals1 implementing the same interface IAnimals:
interface IAnimals
{
public string eat();
}
abstract class Animals implements IAnimals
{
public abstract void run();
public string eat(){ return "Animals eating"; }
}
abstract class Animals1 implements IAnimals
{
public abstract void run1();
public string eat(){ return "Animals1 eating"; }
}
If you now define your Dog class as you did:
class Dog extends Animals,Animals1
{
public void run() {System.out.println("Run method");}
public void run1() {System.out.println("Run1 method");}
}
It will have the method eat() too, which is not abstract so it can use it directly. What would be the return of this method for a dog? Which string will be returned, the one with Animals, or the one with Animals1?
This is called the diamond problem, and it is a reason why in some programming languages it is not allowed multiple inheritance.
Java does not support multiple Inheritance. -" One reason why the Java programming language does not permit you to extend more than one class is to avoid the issues of multiple inheritance of state, which is the ability to inherit fields from multiple classes. " Source https://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
You may find this link useful.
I agree with you(if i understood about what you are talking :) )this is no need of such specific naming conventions.
interface pet
{
public abstract void pet();
}
interface pet1
{
public abstract void pet1();
}
class TestTt implements pet,pet1
{
public void pet()
{
System.out.println("this is method of pet interface");
}
public void pet1() {
System.out.println("this is method of pet1 interface");
}
public static void main(String a[])
{
pet obj=new TestTt();
pet1 obj1=new TestTt();
obj.pet();
obj1.pet1();
}
}
Now, Here if abstract class allows me to create object .then, i can create 2 different references for 2 abstract classes as in interface i can do.
If so, do i need Interfaces...?
In ABSTRACT class,we can't extends multiple abstract classes at a time.
but
In INTERFACE, we can implements multiple interfaces at time.
Therefore , interfaces are used to achieve multiple inheritance in 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
}
I have something like following:
public interface A
{
....
}
public abstract class AbstractClass implements A
{
// Implements some methods from interface
....
}
public abstract class GroupOne extends AbstractClass
{
// Implements some methods from interface
// Define couple of abstract methods
.....
}
public abstract class GroupTwo extends AbstractClass
{
// Implements some methods from interface
// Define couple of abstract methods
.....
}
public class ClassImpl extends GroupOne
{
// Implement couple of abstract methods from GroupOne
}
public class AnotherClassImpl extends GroupTwo
{
// Implement couple of abstract methods from GroupTwo
}
In my case, the interace and abstract classes are provided as part of the library. The application which uses this library needs to write the Impl classes extending the second level abstract ones. There is some common functionality to all classes in AbstractClass and then there is some group specific functionality in the group classes.
Is this a good desgin? The reason I am asking this is I have hardly come across class hierarchy that involved multiple abstract classes.
I see nothing wrong with such a design. ArrayList is one of the most commmonly used classes with two abstract parent classes. It could be useful to make the additional abstract methods of GroupOne and GroupTwo parts of interfaces extending the A 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.