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(){}
}
Related
I have several children of a parent class. I want the parent to implement a method that returns data. However, that data can only ever be correctly populated by the children.
Is this the ideal way to do this in Java? Is there a way to make it so that only the children can call the method?
public class MyParent {
public MyData getData() {
}
}
public class MyChildA extends MyParent {
#override
public MyData getData() {
}
}
Try out, abstract classes.
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
Hope it helps.
Make your parent class an Abstract class.
public abstract class MyParent {
public abstract void getData();
}
public class MyChildA extends MyParent {
#Override
public void getData() {
// statements
}
}
Your question was a bit ambiguous so I don't know if this is what you were looking for.
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);
I have those two interfaces:
public interface ApiResultCallback {
void onSuccess(RestApi.Success<?> successResult);
void onFailure(RestApi.Failure failureResult);
}
public interface GetHappyCowsCallback extends ApiResultCallback {
void onSuccess(RestApi.Success<List<HappyCow>> successResult);
}
Where Success and Failure are:
public static class Success<T> extends ApiResult {
public T data;
}
public static class Failure extends ApiResult {
public String message;
}
I get an error in GetCleverPointsCallback interface saying that
both methods have same erasure but neither overrides the other.
What does that mean? Shouldn't the method from GetHappyCowsCallback override the method of its parent?
What I'm trying to achieve here is some kind of mapping between callbacks and their data without having to implement long mapping functions or even worse, duplicating the Success class like this:
public static abstract class Success<T> extends ApiResult {
public T data;
}
public static class ListHappyCowSuccess extends Success<List<HappyCow>> {
}
void onSuccess(RestApi.Success<?> successResult);
And
void onSuccess(RestApi.Success<List<HappyCow>> successResult);
Do not have the same signature. So the second does not override the first
What you're trying to do can be achieved by making the interface generic:
public interface ApiResultCallback<T> {
void onSuccess(RestApi.Success<T> successResult);
void onFailure(RestApi.Failure failureResult);
}
public interface GetHappyCowsCallback extends ApiResultCallback<List<HappyCow>> {
}
In fact, you probably don't need the second interface at all. Such pseudo-typedefs are even considered an anti-pattern, because the new types cannot be exchanged with their equivalents.
If I have a method like this:
void myMethod(GetHappyCowsCallback callback);
I can not pass an ApiResultCallback<List<HappyCow>> to it.
In most cases interface overriding doesn't really make sense. Unless it involves default methods:
interface InterfaceA {
public void doSomething();
}
interface InterfaceB extends InterfaceA {
#Override
public default void doSomething() {...} // Provides a default implementation
}
I have a question regarding the structures of my classes in java :
I have a first class : MyClass that is abstract
public abstract class MyClass
{
protected void abstract monitor();
}
then I have an abstract iterator on it
public abstract class MyClassIterator<T> extends MyClass
{
protected void abstract monitor(T data);
}
In practice I will after create classes that will either inherit from MyClass or MyClassIterator.
I want to make sure all instances of MyClass implement monitor but for the iterator ones, how can I avoid inserting something like
protected void monitor() {};
just to implement it :/
Thanks for any idea :)
Add a default implementation of monitor in MyClass, with a customized exception
public abstract class MyClass
{
protected void abstract monitor()
{
throw new NotImplementedException();
}
}
Thereby, MyClassIterator won't have to implement the method and other subclasses of MyClass will have to override it.
If you don't want that MyClassIterator subclasses will have to implement this method, then you have to add the empty implementation to MyClassIterator.
You can also throw some exception in the implementation.
public abstract class MyClassIterator<T> extends MyClass
{
protected abstract void monitor(T data);
protected void monitor() {
//optional
throw new UnsupportedOperationException();
}
}
Note: You can't write void before abstract, you need to fix this in your monitor(T data) method, like in my answer.
Im implementing a strategy pattern and in a specific situation, one strategy must use another strategy implementation as part of it.
For Example:
interface ProcessStrategy{
void process();
}
public class ProcessOnFile implements ProcessStrategy{
void process(){
}
}
public class ProcessOnFileNetwork implements ProcessStrategy{
void process(){
}
}
In this case, processOnFileNetwork will encapsulate the logic inside ProcessOnFile plus some especific logic..
How can i add this functionality without repeat the code??
Thanks !
You could use abstract class concept.
public abstract class ProcessStrategy{
public void process(){
// Common code goes here
}
}
public class ProcessOnFile extends ProcessStrategy{
public void process(){
super();
// Class specific code goes here
}
}
public class ProcessOnFileNetwork extends ProcessStrategy{
public void process(){
super();
// Class specific code goes here
}
}
Note abstract classes can have data variables too which can be utilized.
You can make ProcessOnFileNetwork a subclass of ProcessOnFile. That way, you can access the logic in the process() method of ProcessOnFile by calling super.process() in the process() method of ProcessOnFileNetwork.
You probably just typed your code in your question, but just in case, interface and implements must be all lowercase.