Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have two similar classes. I would like to merge it into one. Objects of these classes are used in many different places. Is it possible to do it safely in Eclipse?
If you have two classes that are similar in some ways (but possibly not in others), you could create an Interface that describes the methods that are common to both of them. Then, you would have your two classes implement that Interface. Elsewhere in your application, you could reference the Interface as the formal parameters to your methods. Here's an example (see code below).
There is no automatic way to do this in an IDE-- you've got to take the time to design your object hierarchy (the relationships between your classes, and the API that your application will use to interact with them) manually.
public Interface Automobile{
//define an interface that describes the methods common to your two classes
public void drive();
}
//this is one of your two classes
public class Sedan implements Automobile{
public void drive(){
//Sedan-specific implementation here
}
}
//here's the other one. It's similar in that it has a drive method, but different
//in that it's implementation for drive() is different, and there might be
//other stuff in this class that is different from Sedan. However, it still is-an
//Automoblie
public class RaceCar implements Automobile{
public void drive(){
//RaceCar-specific implementation here
}
}
public class YourApplication{
//some method that accepts either one of the two classes you
//described as being "similar"
public void someMethod(Automobile automobile){
//you could pass in either a Sedan or a RaceCar, and
//the corresponding drive() method would get called
automobile.drive();
}
public static void main(String args[]){
Automobile car1 = new Sedan();
Automobile car2 = new RaceCar();
someMethod(car1);
//call the same method, but with car2!
someMethod(car2);
}
}
Eclipse can't do that automatically, You will have to go to one class, press control+a then control+c then go to the other class and press control+v.
Use Refactor->Extract Interface for each class to create two new interfaces and change the sources to use them instead of the classes.
Now create a new class implementing both these interfaces and remove the old classes. This should only cause your factory methods for the interfaces to break.
Change your factory methods to return this new class and leave all the interface usages in place.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Let's assume that we have an abstract class (let's just call it X) that is inherited by a number of classes (we'll call them A and B for now). Each class that inherits from X does similar, but slightly different things, so while the implementation of each of their public methods might be slightly different, they can all use the same helper functions to avoid duplicating code. However, it makes no sense for any of these helper functions to be accessed by any class that is not a subclass of X.
Furthermore, what if there are a number of helper functions which are only meant to be used inside of classes that extend X, but need to have a slightly different implementation in each class?
Here's an example:
public abstract class X {
public abstract void doStuff();
int helperFunction(int a, int b) {
return a + b;
}
abstract void secondHelperFunction(int x);
}
public class A extends X {
#Override
public void doStuff() {
//do some stuff
helperFunction(a, b);
//so some other stuff
}
#Override
void secondHelperFunction(int x) {
//implementation A
}
}
public class B extends X {
#Override
public void doStuff() {
//do some different stuff
helperFunction(b, a);
//do other stuff
}
#Override
void secondHelperFunction(int x) {
//implementation B
}
}
(This example is obviously very simple, I'm just trying to get my point across)
My question is, what would be the best way to do this? For example, what access modifier should be used for the helper functions? Obviously private isn't an option, since then subclasses wouldn't be able to use it. Default and protected sound like a better choice, but they still allow non-subclasses to use these functions, as long as they are in the same package as X. Would the best solution to this issue then be to enclose X and all classes that inherit from it in their own package, separate from the rest of the program? Or should one perhaps look into another form of abstraction, e.g. interfaces? (Although I cannot think of a way to deal with this using interfaces in particular)
A couple of options for you to consider:
Use protected. You are correct that this does not prevent other classes within the same package from calling the method. But is that really a problem? The idea of a package is to gather related classes together and control the interface through which they are called. Access modifiers are a relatively coarse control mechanism that are designed primarily to help humans avoid errors when coding.
Put the helper functions in a separate class and use composition rather than inheritance. You could still override methods to provide different behaviours. The downside is you will need to pass in any values required. But this isn't necessarily a bad thing as it makes the dependencies clear.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm writing a piece of code for a small card game as a side project in java and have come across an issue I can't find an elagent solution to using OOP.
I have an abstract class Card and then two concrete classes Creature and Machine. What I want to do is have a card that is both a Creature and a Machine, but without creating a new Machine_Creature class as this means writing the same code that creature and machine already have.
I'm looking for a way to create this Machine_Creature class that enables it to obtain the funtionality of both Machine and Creature and prevent me from just copy and pasting the code from one place to another just to enable the functionality
Below is some example code of what my current structure looks like
public abstract class Card {
//Card related methods and attributes
}
public class Machine extends Card {
//Machine related methods and attributes
}
public class Creature extends Card {
//Creature related methods and attributes
}
public class MachineCreature extends Card {
//MachineCreature related methods and attributes
//Problems arise here as we have to rewrite the code Creature and Machine
//already use
}
Java dont allow multiple inheritance. A solution to your problem is to use composition.
Class MachineCreature {
Machine machine;
Creature creature;
...other sepecific methods and attributes
}
Introducing a new level in the hierarchy can solve problem,maintaning the "is a" relationship beetween the objects.I mean
class abstract Card{
//methods
}
class MachineCreature extends Card{
//methods in common beetween Machine and Creature implemented
}
class Machine extends MachineCreature{
//specific methods for Machine class
//optional overloading of parent class
}
class Creature extends MachineCreature{
//specific methods for Creature class
//optional overloading of parent class
}
Otherwise, I don't like very much this solution.
If I were you I would reconsider the solution involving composition given by Patricia.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Consider that I have a class named Validation with five methods. All the methods are very complex and large. In a certain part of my application, I need to create a Validation object, but I'll only be using one method from that object. I could make the method static to fulfill my purpose, but for the rest of the application to keep working, those methods should be non-static.
So is there a way that I can create an object of a class containing only one of the non-static methods?
No.
About the best you can do (to answer the question as asked) is make the method protected and have a subclass of Validation which extends it. Then, if all the other methods are private, that object will only have the one protected one.
It's kind of a bad situation, though. More than likely, if you're trying to do this, you're either trying to optimize for no reason or you have a bad design somewhere.
e.g.,
public class Validation {
private void method1() {}
private void method2() {}
protected void method3() {}
private void method4() {}
}
...
public class RestrictedValidation extends Validation { }
...
public static void main(String[] args) {
RestrictedValidation validation = new RestrictedValidation();
validation.method1(); //compiler error
validation.method2(); //compiler error
validation.method3(); //success
validation.method4(); //compiler error
}
But yeah. I can't think of a single valid use-case for this.
You can solve this by way of inheritance where ValidationA would contain common methods used by most clients (here your one particular method), and a ValidationB class which extends ValidationA and add more specialized methods.
Or depending of the situation, it could be 2 completely different objects.
No there is no such way. An object consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods. Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication.
what you is saying is create a person object(whose has already defined behaviour of walking and running) but he should only walk and not run. It does not make sense.
Jeff Gohlke provided a good solution to it
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
What's the utility of interfaces other than abstraction and providing a workaround for multiple inheritance ?
If there is an Interface I having method m1() which is implemented by class A and another class B wants to access the method m(), what is the need of interface here.
Can we simply not implement that method in class A? like -
public class A implements I {
public void m1() {
// business logic goes here
}
}
public class B {
A objectOfA = new A();
objectOfA.m1;
}
This is a basic Object Oriented Programming problem. I suggest you to read OOP. Interface help to decouple your design and implemention, make it easier to reuse code. Also recomand some materials about design patterns. Head First Design Patterns is a good start and not that hard.
Put simply, an Interface is a contract. A good example is the List Interface.ArrayList and LinkedList implement the List Interface. We know that. You also know that java.util.Collections provides methods for interfaces, like sort().
The point is, this very code can be used to sort() either the ArrayList or a LinkedList, because they implement the List interface, but you can also write your own code to implement more cooler things.This way, people can use your code without having to ask you to support their classes.
Yes we can simply implement that method in class A. But let be give a example of Interface so that you can understand your code. There is a concept of Re-usability in OOPs.
An interface defines a new secondary
datatype in Java.
An interface is a reference type only
its objects cannot be created.
An interface can inherit another interface
but cannot inherit any class.
A class cannot inherit any interface but
it (a class) can implement zero to many
interfaces.
If a class implements interfaces then
1) It has to override all the abstract
methods of all the implemented interfaces.
2) Type compatibilty gets created between
the interface and the class. It allows an
interface reference can refer to object
of implementing class.
*/
interface Iface
{
int x = 3;//final and public by default
void f();//abstract and public by default
}
interface AnotherI extends Iface
{
//more declarations possible here
}
class InterfaceDemo implements Iface
{
public void f()
{
int i;
for(i =0 ; i< x; i++)
System.out.println("Interfaces are widely used");
}
public static void main(String args[])
{
Iface ref = new InterfaceDemo();
ref.f();//allowed
//ref.newMethodsOfClass();//not allowed
}
}
A practical example
List<String> list;
list = thereIsMuchData ? new ArrayList<>() : new LinkedList<>();
public void f(List<String> strings) { ... }
List being an Interface, ArrayList and LinkedList implementing classes.
You can see the following:
The implementation is your choice, based on technical knowledge. In this java distinghuishes itself from simple languages where there is one-fit-all List.
Usage of list is not overspecific.
The method f can handle all kind of lists.
I agree with #IdleMind. Also interface force you to implement all the method(s) containing the interface. You can say it is a contract to your concrete class(s) where you have implemented it.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In all examples I have seen that interfaces are used to achieve polymorphism. Now we have the following code with abstract class
AbstractClass parent = new Child();
Here the man stated that
A common argument is that Polymorphism only applies to interfaces and
not abstract classes.
I think he meant they are usually interfaces that are used in polymorphism in Java. As I see many people found his question silly and wanted URL. This here what I found. So my question is it a good/common practice to use abstract classes in polymorphism (as in my example - because polymorphism is very wide definition) in Java?
It is good practice to use the most general parent that meets the contract; if the interface defines all of the function signatures you need then use them rather than abstract classes implementing that interface. The article Design Principles from Design Patterns by Bill Venners in discussion with Erich Gamma goes into detail.
One of their best uses is where you have a common behaviour between "childs".
Your interface
interface Drawable{
void paint();
}
An abstract class with common code
abstract class AbstractRectangularObject implements Drawable{
public void paint(){
paintVertices();
//your code to fill body
}
//Abstract method that all subclases needs to implement
protected abstract void paintVertices();
}
Your real subclasses
class Rectangle extends AbstractRectangularObject {
protected void paintVertices(){
//code to pain vertices
}
}
-
class RoundRectangle extends AbstractRectangularObject {
protected void paintVertices(){
//code to pain vertices
}
}
If You have common functinality and properties to share between child classes and at the same time the class itself is too abstract to have instance, it will be good practice to use abstract class. If no I will prefer to use interfaces.
In general, yes. It is always good practice to use the least specific type necessary. This applies in to concrete super classes, too, not just abstract classes and interfaces.
public class MyClass{} // not an interface and not abstract
public class SubClass extends MyClass{}
public class OtherClass{
public MyClass getMyClass(){
return new SubClass();
}
]
In practice, it depends on the situation. If everything is contained within the scope of say one method, it really doesn't matter.
public void doStuff(){ // void method, so never going return any details
AbstractFoo foo1= new ConcreteFoo();
// no better than
ConcreteFoo foo2 = new ConcreteFoo();
// because nothing external to this method will ever know
}
However, the reason behind having developers always use the least specific implementation (or interface) is to just make it a habit.
Answer depends on your context.
Example:
// Abstract class template
abstract class AbstractFirst {
public void doSomething(){
this.doOne();
this.doSecond();
System.out.println("");
System.out.println("Test");
}
public abstract void doOne();
public abstract void doSecond();
}
// Concrete implementation
class ConcreteFirst extends AbstractFirst {
public void doOne(){System.out.print("One"); } // must be implemented
public void doSecond(){System.out.print("Second"); } // must be implemented
public static void main(String[] args){
ConcreteFirst cf = new ConcreteFirst();
c.doSomething();
}
}
This prints
OneSecond
Test
to console. This is not possible with Interfaces. This pattern is called "Template method pattern" and is one of the GoF Patterns
As to my experience, abstract class always contains partial implementation of some interface. This is the case for EJBs, for example. Its a better design to keep API and its implementation separate, even partial. So Id recommend make an interface and an abstract class. But for references use interface rather then abstract class.
Regarding to your question there's not such opinion that say it's a bad practice to use polimorphism, it's a good practice to use it where it applies, but it depends on usecases where you define the requirements for the classes to be pure virtual aka interfaces.