I have got multiple classes which each implement multiple different methods within each. Now the problem statement is that I wish to use the methods from all these (maybe around ~200 such different class files/methods) in another class file which all different methods from the above class files.
I thought that if I implement an interface which has all these various methods listed, then I just call/import/reference that single interface and can use all the methods? But I am stuck, as this solution does not seem to work.
The opposite of the above works (i.e. single class implements 2 interfaces: http://tutorials.jenkov.com/java/interfaces.html). Wish to check if the single interface can use multiple classes, without the overhead of declaring all the methods in each class that is being referenced inside the Interface?
As an example: Is there any way in which I can implement 2 different classes in the same interface, without each having the abstract class for each? As if the class is abstract, then I am unable to use the methods from it in the below example "Application" class:
Common commonClass = new ABC_FamilyGivenName();
The above is not allowed, if the ABC_FamilyGivenName class is an abstract class.
INTERFACE:
public interface Common {
void ABC_GivenNames();
void ABC_FamilyNames();
void ABC_Gender();
void ABC_BirthDay();
}
IMPLEMENTATION CLASSES:
public class ABC_FamilyGivenName extends Base implements Common {
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
}
public class ABC_DOBGender extends Base implements Common {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
}
USE IMPLEMENTED CLASS:
public class Application extends Base {
Common commonClass = new ABC_FamilyGivenName();
/* DO I NEED THIS? I THINK I DO, BUT CODE/JAVA SAYS I DO NOT
* Common commonClass = new ABC_DOBGender();
*/
public void ELP_C0050_PassportDetails(){
commonClass.ABC_GivenNames();
commonClass.ABC_FamilyNames();
commonClass.ABC_DOB();
commonClass.ABC_Gender();
}
}
I have 2 classes called ABC_FamilyGivenName & ABC_DOBGender.
I have created an interface Common.
I want to use the methods in both the above classes in another class called Application.
With the current implementation, Java wants me to add an #Override to both the ABC_FamilyGivenName & ABC_DOBGender:
IMPLEMENTATION CLASSES:
public class ABC_FamilyGivenName extends Base implements Common {
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
#Override
public void ABC_BirthDay() {}
#Override
public void ABC_Gender() {}
}
public class ABC_DOBGender extends Base implements Common {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
#Override
public void ABC_GivenName() { }
#Override
public void ABC_FamilyName() { }
}
Can I avoid the above #Override and just use the classes without these as given in the first example?
Object-oriented programming in Java requires to "override" all methods, if you are implementing a method, otherwise you may use inheritance, so not all methods must be overriden.
In your case you may put all four methods to parent class Base and then inherit them.
Then the interface class is not needed or make two different interfaces.
To implement Java interface, You should override all the abstract methods are declared into the interface. It is a basic concept of interface. Here interface Common all four methods are abstract, So you should override them. Otherwise, Java compiler will throw a compilation error. So better way can be splitting the interface into 2 parts.
It is a contractual nature of an interface the subclass who implement the interface should have all the activities of the interface. It is the main purpose of using an interface.
If you don't wanna override all the method of interface but you need to use the interface as a reference of every class, then you can use a concrete class instead of interface and inherit the concrete class to every class
To implement the below code change please make sure you use java8
public interface Common {
default public void ABC_GivenNames() {
}
default public void ABC_FamilyNames() {
}
default public void ABC_Gender() {
}
default public void ABC_BirthDay() {
}
}
IMPLEMENTATION CLASSES:
public class ABC_FamilyGivenName extends Base implements Common {
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
}
public class ABC_DOBGender extends Base implements Common {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
}
Can I avoid the above #Override and just use the classes without these
as given in the first example?
No, in java you have to implement all methods of interface unless its abstract class
as suggestion you can create two separate interfaces,
for more detail see : not implementing all of the methods of interface. is it possible?
You can provide an empty implementation for all the methods of an interface in other class called Adaptor class. And you can extend that adaptor class in ABC_FamilyGivenName class and ABC_DOBGender class.
class Adaptor implements common
{
public void ABC_GivenNames() {
}
public void ABC_FamilyNames() {
}
public void ABC_Gender() {
}
public void ABC_BirthDay() {
}
}
IMPLEMENTATION CLASSES :
public class ABC_FamilyGivenName extends Adaptor{
public void ABC_GivenNames(){
// Implementation code
}
public void ABC_FamilyNames(){
// Implementation code
}
}
public class ABC_DOBGender extends Adaptor {
public void ABC_Gender(){
// Implementation code
}
public void ABC_BirthDay(){
// Implementation code
}
}
interface Icalculate{ //interface
calculate(operand1:number,operand2:number):number
}
class Add implements Icalculate{ //addition
calculate(operand1: number, operand2: number): number{
return (operand1 + operand2);
}
}
class Sub implements Icalculate{ //subtraction
calculate(operand1: number, operand2: number): number{
return (operand1 - operand2);
}
}
class Mul implements Icalculate{ //multiplicationn
calculate(operand1: number, operand2: number): number{
return(operand1*operand2);
}
}
class Div implements Icalculate{ //Division
calculate(operand1: number, operand2: number): number{
return(operand1/operand2);
}
}
let a = new Add;
let b = new Sub;
let c = new Mul;
let d = new Div;
class Calculator { //main class
operator: Icalculate;
operand1: number;
operand2: number;
constructor(a: number, b: number, operator: Icalculate) {
this.operand1 = a;
this.operand2 = b;
this.operator = operator;
let op = this.operator;
console.log(op.calculate(this.operand1, this.operand2));
}
}
const cal=new Calculator(1,1,a);
Related
I'm working on a java exercise that has me a bit confused. How can I use polymorphism while the methods are in an interface? Some help would be appreciated.
Setters and getters can be omitted.
What I have so far:
Interface:
interface Interface {
public void start();
public void stop();
}
First Class:
class Class1 implements Interface {
private String brand;
#Override
public void start() {
System.out.println("Hello from start"); }
#Override
public void stop() {
System.out.println("Hello from stop");}
}
Class 2:
class Class2 implements Interface {
private String plate;
#Override
public void start() {
System.out.println("Hello from start");
}
#Override
public void stop() {
System.out.println("Hello from stop");}
}
Aggregation Class:
class Aggregate {
private String destination;
private String starting;
public void trip(interface : Interface) {
interface = new Aggregate(Interface);
}
}
An interface in java, is a collection of abstract methods. When a class implements an interface, it inherits the abstract methods of the interface, so that the class can add a body to those methods specifically for itself. In other words, the class can override those methods mentioned in the interface. I believe you know that overriding and overloading are two types of polymorphism in java. So, in your answer above, you have indeed used polymorphism correctly. Just, add a simple method body relevant to the class, like printing something to the screen (as mentioned in the assignment), in order to add more meaning.
This question was asked to me in an interview. Tired of googling here I am.
I have an interface with 100 methods. I don't want to implement all those 100 methods in a single class. Is there any way I could implement these 100 methods by using more than one class and not repeating the implementation ?
For Example :
Class A implements first 10 methods(only).
Class B implements next 10 methods(only) and so on.
Note :
1. All the classes which implements the interface must be concrete.
As far as my knowledge on java this isn't possible. He mentioned about adapter when he asked me this question. That made me think that there's a way to do it.
Can anybody clarify me on this ?
Write an adapter with empty implementation of the 100 methods
class Adapter{
//write your empty implementations here as similar to KeyListener in Java
// They have written a keyAdapter and make use of key adapter.
}
ie) class Adapter implements interface1{
public void method1(){}
public void method2(){}
.....
}
You can extend the adapter class in some other class and just override the methods.
class A extedns Adapter{
public void method1(){
}
}
ie)
The concept you describe is called partial classes and Java does not have such a concept.
Here is a similar answer: A way to implement partial classes in java
If you use Java 8 , you can define default implementations in the interface for the 100 methods like :
public interface MyInterface{
void methodA();
int methodB();
default boolean methodC(String name) {
return name.equals("Default");
}
}
Then in your concrete classes you only implements the methods you want. All other not overriden methods will use the default implementation from the interface.
You will have to write 100 default implementations in the interface but it will save you the need to also write 100 implementations in every concrete class implementing that interface.
Again, this is only available since Java 8.
Write all the classes (A, B, C, D, E each implement 20 methods) witch extend one another without implementing the interface I:
I
|
A <- B <- C <- D <- E
And only the last one implements the interface.
Simpler exemple with only 2 methods:
public interface I {
void a();
void b();
}
public class A {
public void a() {
}
}
public class B extends A implements I {
public void b() {
}
}
If the interface methods defined with default implementation ;
public interface I {
default void a(){
//implementation
}
default void b(){
//implementation
}
default void c(){
//implementation
}
//97 more
}
public class A implements I{
#override
public void a() {
}
}
public class B extends A {
#override
public void b() {
}
public class C extends B {
#override
public void c() {
}
}
Even without inheritance classes can be independent from each other and they can provide implementation for different methods
You are correct - any concrete class must implement all methods, so the only way you can not do it is either extend the class that implements given interface and override some of the methods in subclass or implement methods calling implementations from other classes
Greetings and salutations!
I currently have an abstract class A, and many classes subclassing it. The code is common to all the subclasses I've put in the oneMethod() and the code that's specific to each implementation I've put into two abstract methods.
public abstract class AbstractA {
public oneMethod() {
//do some intelligent stuff here
abstractMethodOne();
abstractMethodTwo();
}
protected abstract void abstractMethodOne();
protected abstract void abstractMethodTwo();
}
I have a class that overrides the oneMethod() method.
public class B extends AbstractA {
#Override
public oneMethod() {
//do some other intelligent stuff here
}
}
Is there any way to skip making a stub implementation of the two abstract methods in the subclass? I mean the only place they're used is in the overridden method.
Any help is appreciated!
No. If you extend an abstract class, you must either make the child class abstract or it must fulfill the contract of the parent class.
As a design observation, I would suggest that you try to make oneMethod() either final or abstract. It's hard to maintain programs that allow extension the way you're implementing it. Use other abstract methods to give child classes hooks into the functionality of oneMethod().
You have to provide an implementation to all abstract methods. Even if no part of the program calls them now a class can be created in the future that does call them, or the super class implementation may be changed. A stub is needed even if it's just for binary compatibility.
Just make class B also abstract.
public abstract class B extends AbstractA {
You could pull oneMethod up into a superclass:
public abstract class AbstractC {
public void oneMethod() {
}
}
public abstract class AbstractA extends AbstractC {
#Override
public void oneMethod() {
//do some intelligent stuff here
abstractMethodOne();
abstractMethodTwo();
}
protected abstract void abstractMethodOne();
protected abstract void abstractMethodTwo();
}
public class B extends AbstractC {
#Override
public void oneMethod() {
//do some other intelligent stuff here
}
}
see now how you don't need any more in AbstractC than you need.
Since abstractMethodOne() and abstractMethodTwo() are implementation specific but you know that you will always call them you can use composition like this:
public interface SomeInterface {
void abstractMethodOne();
void abstractMethodTwo();
}
and create a class like this:
public class SomeClass {
public void executeThem(SomeInterface onSomeObject) {
onSomeObject.abstractMethodOne();
onSomeObject.abstractMethodTwo();
}
}
then you can compose this in any of your classes where you should call those methods like this:
public class SomeImplementation implements SomeInterface {
public void abstractMethodOne() {
// ...
}
public void abstractMethodTwo() {
// ...
}
public void executeThem() {
new SomeClass().executeThem(this);
}
}
This way you got rid of the inheritance altogether and you can be more flexible in your classes implementing SomeInterface.
If your classes B and A have to implement their own oneMethod it's maybe because there are not in an inheritance link but they just should implement the same interface ?
Well, if abstractMethodTwo and abstractMethodOne are implementation specific, why you put these methods in the base abstract class ? Maybe a common interface or some specific design-pattern is what you're looking for!
An abstract method from an abstract class can be used in a class in the way shown below. I would appreciate your opinion if you find any wrong in my answer. Thank you.
Code using Java
public abstract class AbstractClassA {
protected abstract void method1();
public abstract void method2();
}
public class ClassB extends AbstractClassA{
#Override
protected void method1(){}
public void method2(){}
}
I have the following setup:
class Base {};
class ImplA extends Base {};
class ImplB extends Base {};
class ImplC extends Base {};
Base baseFactory(int type) {
switch(type) {
case 0:
return new ImplA();
case 1:
return new ImplB();
case 2:
return new ImplC();
}
Base a = baseFactory(0);
Base b = baseFactory(1);
Base c = baseFactory(2);
List<Base> list = new ArrayList<Base>();
list.add(a);
list.add(b);
list.add(c);
// Somewhere else I have:
interface BaseHandler {
process(ImplA a);
process(ImplB b);
process(ImplC c);
};
Now, what I would like to be able to do is something along the lines of:
class Processor {
BaseHandler bh;
Processor(BaseHandler bh) {
this.bh = b;
}
void processList(List<Base> list) {
for (Base x : list) {
bh.process(x);
}
}
And then have a user implement BaseHandler and be able to construct a Processor to operate on each element in the Base list.
But, this does not work as process(Base) is not defined. It may seem simple to just add 3 if statements, but I already have a switch like structure in building instances of classes extending the Base. It seems unnecessary to repeat this over and over. Is there a way to achieve this idea without writing an intermediate step that determines the runtime class of each Base in the list and calls the appropriate method (in effect another switch case -- but it would be if's)?
I think one work around idea would be to make each Base have an abstract process method which needs to be implemented by the Impl classes. However, this is not acceptable in my situation since the user will not be implementing the Impl classes. Basically, I need process to be a user-defined callback. Further, it does not make sense for process to be a member of the Impl or Base classes since it is in no way related. It's a separate callback that needs to respond dynamically to the type it is called with. And the type is always guaranteed to be a subclass of Base.
You do need the "intermediate step" that you describe, but it need not be if statements. What you're looking for is double dispatch using the visitor pattern. Basically your Base class would have a method:
void accept(BaseHandler handler);
and each subclass would implement it as:
handler.process(this);
where this would resolve to the correct type in each subclass at compile-time.
What you're looking for is the Visitor pattern. You put an abstract method on Base, but all it does is call the appropriate method in BaseHandler:
public interface Base {
void acceptHandler(BaseHandler handler);
}
Then your concrete implementations override acceptHandler and call the correct overload.
public class ImplA implements Base {
public void acceptHandler(BaseHandler handler) {
handler.process(this);
}
}
At this point there's not much value in the overloading, and you'd be better off just giving your methods descriptive names.
It sounds like what you want is the Visitor pattern here:
public interface BaseVisitor {
void caseA(ImplA a);
void caseB(ImplB b);
void caseC(ImplC c);
}
public class MyVisitor implements BaseVisitor {
void visit(List<Base> bases) {
for (Base b : bases) {
b.accept(this);
}
}
public void caseA(ImplA a) { // ... }
public void caseB(ImplB b) { // ... }
public void caseC(ImplC c) { // ... }
}
public abstract class Base {
abstract void accept(BaseVisitor visitor);
}
public class ImplA {
public void accept(BaseVisitor visitor) {
visitor.caseA(this);
}
}
public class ImplB {
public void accept(BaseVisitor visitor) {
visitor.caseB(this);
}
}
public class ImplC {
public void accept(BaseVisitor visitor) {
visitor.caseC(this);
}
}
I'm looking to create a set of functions which all implementations of a certain Interface can be extended to use. My question is whether there's a way to do this without using a proxy or manually extending each implementation of the interface?
My initial idea was to see if it was possible to use generics; using a parameterized type as the super type of my implementation...
public class NewFunctionality<T extends OldFunctionality> extends T {
//...
}
...but this is illegal. I don't exactly know why this is illegal, but it does sort of feel right that it is (probably because T could itself be an interface rather than an implementation).
Are there any other ways to achieve what I'm trying to do?
EDIT One example of something I might want to do is to extend java.util.List... Using my dodgy, illegal syntax:
public class FilterByType<T extends List> extends T {
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
}
You can achieve something like this using a programming pattern known as a 'decorator' (although if the interface is large then unfortunately this is a bit verbose to implement in Java because you need to write single-line implementations of every method in the interface):
public class FilterByType<T> implements List<T> {
private List<T> _list;
public FilterByType(List<T> list) {
this._list = list;
}
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
// Implement List<T> interface:
public boolean add(T element) {
return _list.add(element);
}
public void add(int index, T element) {
_list.add(index, element);
}
// etc...
}
Alternatively, if the methods don't need to access protected members, then static helper methods are a less clucky alternative:
public class FilterUtils {
public static void retainAll(List<T> list, Class<?> c) {
//..
}
public static void removeAll(List<T> list, Class<?> c) {
//..
}
}
What prevents you from just adding new methods to the interface?
If you can't just add the new functionality to old interface, you could consider making another interface and then an implementation which merely implements those two. Just to be clear, in code this is what I mean:
// Old functionality:
public interface Traveling {
void walk();
}
// Old implementation:
public class Person implements Traveling {
void walk() { System.out.println("I'm walking!"); }
}
// New functionality:
public interface FastTraveling {
void run();
void fly();
}
// New implementation, option #1:
public class SuperHero extends Person implements FastTraveling {
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
// New implementation, option #2:
public class SuperHero implements Traveling, FastTraveling {
void walk() { System.out.println("I'm walking!"); }
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
I think it's illegal because you can not guarantee what class T will be. Also there are technical obstacles (parent's class name must be written in bytecode, but Generics information get lost in bytecode).
You can use Decorator pattern like this:
class ListDecorator implements List {
private List decoratingList;
public ListDecorator(List decoratingList){
this.decoratingList = decoratingList;
}
public add(){
decoratingList.add();
}
...
}
class FilterByArrayList extends ListDecorator {
public FilterByAbstractList () {
super(new ArrayList());
}
}
There is a delegation/mixin framework that allows a form of this. You can define a new interface, implement a default implementation of that interface, then request classes which implement that interface but subclass from elsewhere in your hierarchy.
It's called mixins for Java, and there's a webcast right there that demonstrates it.
I'm afraid it's not clear what do you want to get.
Basically, I don't see any benefit in using 'public class NewFunctionality<T extends OldFunctionality> extends T' in comparison with 'public class NewFunctionality extends OldFunctionality' ('public class FilterByType<T extends List> extends T' vs 'public class FilterByType<T> implements List<T>')