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 2 years ago.
Improve this question
Hi friends!
I'm trying to do my homework. Now I am busy with the Cone.java part.
(F) balls >>> Flavor[]
How can I define that?
Well to break it down a bit for you.
Cone is a class that implements Eatable.
It has a field called balls. This is an array of type Flavors.
It also has two constructors. A basic constructor that has no arguments and a constructor that takes an array of type Flavors.
Finally it has a method called eat. This comes from the interface Eatable.
This would look a little like the following.
Eatable.java
public interface Eatable {
void eat();
}
Cone.java
public class Cone implements Eatable {
//The types of flavors
public enum Flavors {
STRAWBERRY,
BANANA,
CHOCOLATE,
VANILLA,
LEMON,
STRACIATELLA,
MOKKA,
PISTACHE
}
//The field
private Flavors[] balls;
//The constructors
//Constructor Basic
public Cone() {
balls = new Flavors[0];
}
//Constructor with Flavors
public Cone(Flavors[] balls) {
this.balls = balls;
}
//The methods
//You should always use getters and setters
//https://stackoverflow.com/questions/1568091/why-use-getters-and-setters-accessors
//Getter
public Flavors[] getBalls() {
return balls;
}
//Setter
public void setBalls(Flavors[] balls) {
this.balls = balls;
}
//Your method from UML
#Override
public void eat() {
//Whatever
}
}
This is simply a Dependency relation. You need to draw a dashed arrow from Cone to Flavor. This is because Flavor is an enumeration (the Mickeysoft or Eclipse notation you're using is wrong by the way, but you probably can't alter that except by staying away from the tool itself). The enumeration is used for balls to form an array of Flavors.
Related
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 1 year ago.
Improve this question
my question is more a personnal mind challenge than a production purpose... which means that despite there are obviously better ways to achieve my goal* , I am curious about how - AND IF - I could do it this way.
*I am thus not interested in other ways atm.
I would like to "register" within a list several classes objects (Foo.class, Bar.class, etc.) sharing a common static method inherited from a common parent class.
Then I want to iterate over this list, and invoke that static method.
The following code is wrong indeed, but it may at least show what I am trying to achieve:
======== Classes definition
public class SomeGenericClass {
public abstract static String getType();
}
public class SomeSpecializedClassA extends SomeGenericClass{
public static String getType(){
return "I am of type A";
}
}
public class SomeSpecializedClassB extends SomeGenericClass{
public static String getType(){
return "I am of type B";
}
}
======== Main
class Main{
void main(){
List<Class<SomeGenericClass>> classes = new ArrayList<Class<SomeGenericClass>> ();
classes.add(SomeSpecializedClassA.class);
classes.add(SomeSpecializedClassB.class);
for((SomeGenericClass.class)Class c : classes){
System.out.println(c.getMethod("getType", null).invoke(null, null));
}
}
}
========
Any idea?
sharing a common static method inherited from a common parent class.
This is impossible; static methods do not 'do' inheritance, hence why they are called static methods. There is NO way to specify that a given class adheres to a spec, where 'the spec' involves 'has static method XYZ'.
Why do you think java has the cliché of having 'factories'? A factory is just a container concept where a single instance of a class is the place you ask questions about the concept of another class: A "PersonFactory" is a class for which usually only a single instance exists and it answers questions about persons in general. Most usually the constructor (which doesn't 'do' specs/interfaces either), but anything else goes too.
Then I want to iterate over this list, and invoke that static method.
Reflection can do this. It'd be horrible code style, hard to maintain, and all around entirely the wrong way to go about it. You're asking me: "May I have a gun because there is an annoying mosquito balanced on my left toe", and that's the bazooka. If you want to take it and let er rip, okay. Your funeral.
So what's the better way?
Why is 'static' important here? It's not. Register 'TypeOracle' objects:
public interface CommandHandlerFactory {
String getCommand();
CommandHandler makeHandler();
}
public interface CommandHandler {
void handleCommand(UserInfo sendingUser, String cmdData);
}
public class WelcomeHandler {
#Override
public void handleCommand(UserInfo sendingUser, String cmdData) {
sendMsg("Well hello there, " + sendingUser.getUserName() + "!");
}
}
channelBot.registerHandler(new CommandHandlerFactory() {
#Override
public String getCommand() {
return "/hello";
}
#Override
public CommandHandler makeHandler() {
return new WelcomeHandler();
}
}
That's how you do it in a non-blow-your-feet-right-off fashion.
NB: A comment on your question suggest using asm. This is an utterly nonsensical comment; ASM has nothing to do with this and can't help you. Ignore this comment.
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 4 years ago.
Improve this question
I have an interfaceFileService
And an implementation of it FileServiceBean
I want to be able to process multiple filetypes.
e.g. fileService.processFile(FileDescriptor);
Where, the fileDescriptor is a class e.g.
public class FileDescriptor {
#Column(name = "FILE_TYPE")
protected String fileType;
}
Then I want multiple extensions of the FileServiceBean to process different filetypes. And FileServiceBean would have all the methods common to all filetypes.
e.g.
PhotoProcessingBean extends FileProcessingBean
VideoProcessingBean extends FileProcesingBean
How do I make the interface decide what implementation to use? I am rather new to this and not really quite sure how to ask the question to search google for the answer.
Ideally it would not just accept FileDescriptor. e.g. It could be something else like just File.
fileService.processFile(Object);
Well, in the end you have to put the decision logic somewhere, the only question is where?
I think this is a classic application of the factory-pattern: you create an object (the "factory") which has the sole purpose of deciding which concrete implemenation of a common interface to create for a given case. See https://en.wikipedia.org/wiki/Factory_method_pattern
Along the lines of:
PhotoProcessingBean extends FileProcessingBean {...}
VideoProcessingBean extends FileProcesingBean {...}
class FileProcessingFactory {
public static FileService createFileService(FileDescriptor descriptor) {
switch(descriptor.getFileType()) {
case 'Photo': return new PhotoProcessingBean();
case 'Video': return new VideoProcessingBean();
default: // do some error handling
}
}
}
And using it:
for(FileDescriptor descriptor : /* wherever they come from */) {
FileService processor = FileProcessingFactory.createFileService(descriptor);
processor.processFile(descriptor);
}
Sure enough you can also soften up the interface by accepting objects instead of file descriptors. This depends on the concrete application.
Assuming you have an interface:
public interface IFileService{
void processFile();
}
And the FileProcessingBean class that implements this:
public class FileProcessingBean implements IFileService{
//other code here
#Override
public void processFile(){
//add code for implementation of method
}
}
If you have two other classes that extend FileProcessingBean:
public class PhotoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing PHOTO...");
}
}
public class VideoProcessingBean extends FileProcessingBean{
#Override
public void processFile(){
System.out.println("Processing VIDEO...");
}
}
If you would like to use it:
//This is an OOP concept called Polymorphism:
IFileService photoProcess = new PhotoProcessingBean();
IFileService videoProcess = new VideoProcessingBean();
Calling photoProcess.processFile(); and videoProcess.processFile() would yield different the implementations:
photoProcess.processFile();
videoProcess.processFile();
And you'll get the following output:
Processing PHOTO...
Processing VIDEO...
Regarding your point about not just accepting FileDescriptor but also 'something else', my recommendation would be to either know exactly what sort of arguments you are expecting, and then either implementing overriding methods or via an interface. It would not be wise to use Object as a method argument as Object is a superclass from which all objects are descendants of. You would essentially be opening the 'floodgates' and potentially run into runtime errors.
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 6 years ago.
Improve this question
I was working on this question and I was wondering I have got it right.
Consider the interface MusicInterface which has a constant data member, TYPE,
which is equal to ‘Nice Music’ and a method play() which displays the TYPE on
console. The class StringedInstrument implements the interface
MusicInstrument.
i) Write the Java code for the interface MusicInstrument.
ii) Implement the abstract class StringedInstrument having variables
numberOfStrings of type integer and name of type String. No
implementation of method play is possible at this point.
iii) Implement the concrete class ElectricGuitar which is a subclass of
StringedInstrument having a constructor that initializes the name and
numberOfStrings and appropriate methods.
MusicInstrument class
public interface MusicInterface {
final String TYPE= "Nice Music";
public void play();
}
StringedInstrument class
public abstract class StringedInstrument implements MusicInterface {
public int numberOfStrings;
public String name;
}
ElectricGuitar class
public class ElectricGuitar extends StringedInstrument{
public ElectricGuitar(int numberOfString, String name){
super();
}
#Override
public void play() {
System.out.println("The type of music is: "+TYPE);
}
}
The question seems to be pretty straightforward so I was wondering if I made any mistake in understanding it.
Some notes for writing conventional Java code:
Change the visibility of the declared fields in your Abstract class StringedInstrument to be at least protected (or package-private). These fields are part of the state of the class and should be properly encapsulated.
Also, your ElectricGuitar constructor is kinda useless. It receives 2 parameters that are never used and the StringedInstrument's respective fields remain uninitialized. You should create a matching constructor in StringedInstrument and initialize the numberOfStrings and name fields in it, something like:
public StringedInstrument(int numberOfString, String name){
this.numberOfStrings = numberOfStrings;
this.name = name;
}
and ElectricGuitar would use this super constructor:
public ElectricGuitar(int numberOfStrings, String name){
super(numberOfStrings, name);
}
There is no particular reason for the class StringedInstrument to be abstract if it does not include any polymorphic abstract methods. I don't think this context would satisfy an appropriate example of abstract inherency.
That being said, whether you make it abstract or not, you should include in StringedInstrument:
public StringedInstrument(int numberOfStrings, String name) {
this.numberOfStrings = numberOfStrings;
this.name = name;
}
and in Electric guitar:
public ElectricGuitar(int numberOfStrings, String name) {
super(numberOfStrings, name);
}
I suppose if you put the TYPE in StringedInstrument you could do:
public abstract String getType();
and then in your specific class (ElectricGuitar) customize what getType() produces which is also a pretty weak use of an interface.
public abstract class StringedInstrument implements MusicInterface {
public int numberOfStrings;
public String name;
public StringedInstrument()
{
// This gets called by ElectricGuitar() constructor
}
#Override
public void play()
{
// I meant, you can also HAVE AN IMPLEMENTATION HERE. My Corrections
// OMITTING THIS METHOD BODY DECLARATION, WON'T CAUSE COMPILE ERRORS
// THAT WAS A BAD JOKE BY ME
System.out.println("The type of music is: "+TYPE + " In " + this.getClass().getSimpleName() );
}
}
Your Code stands solid
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 8 years ago.
Improve this question
I would like to create a programme based on a robot scenario, that includes abstract classes, interface types and array lists. Can anyone give me some advice on how to create this scenario (via a UML diagram to show how everything links). This scenario needs to include some complex methods, but I am unsure of what to do as a complex method or where to place them in the scenario. Thanks in advance.
The world of programming has, for the most part, moved on from complex inheritance hierarchies and instead embraced composition and dependency injection. I suggest you break your monolithic services into small (1-5 method) interfaces. This has the added benefit that unit testing becomes a breeze since you can mock out the dependencies with mockito or similar.
eg:
public interface Walkable {
void walk(Robot robot, int paces);
}
public interface Talkable {
void talk(Robot robot, String phrase);
}
public interface Robot {
void walk(int paces);
void talk(String phrase);
}
public class RobotImpl implements Robot {
private final Walkable walkable;
private final Talkable talkable;
public RobotImpl(Walkable w, Talkable t) {
this.walkable = w;
this.talkable = t;
}
public void walk(int paces) {
walkable.walk(this, paces);
}
public void talk(String phrase) {
talkable.talk(this, phrase);
}
}
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 8 years ago.
Improve this question
We had a discussion in the office, but neither side was convinced. Lets say we have
enum Food {
CHICKEN, HAMBURGER, FISH;
}
We need multiple implementations of Dog, which need to answer, whether they are happy, which depends on whether they like food given to them and maybe some other stuff. It needs to be very flexible. Which is better:
A:
abstract class Dog {
//not sure if this can be abstract in reality, but does it matter?
abstract Set<Food> getFavoriteFoods();
boolean isFoodOk(){
return getFavoriteFoods().contains(Food.CHICKEN);
}
//in reality sometimes more conditions are needed here...
boolean isHappy(){
return isFoodOk();
}
}
public class BullDog extends Dog {
static final Set<Food> FAVORITE_FOODS = new HashSet<Food>();
static {
FAVORITE_FOODS.add(Food.CHICKEN);
FAVORITE_FOODS.add(Food.FISH);
}
Set<Food> getFavoriteFoods(){
return FAVORITE_FOODS;
}
}
OR B:
abstract class Dog {
abstract boolean isHappy();
boolean isFoodOk(Set<Food> f){
return f.contains(Food.CHICKEN);
}
}
public class BullDog extends Dog {
static final Set<Food> FAVORITE_FOODS = new HashSet<Food>();
static {
FAVORITE_FOODS.add(Food.CHICKEN);
FAVORITE_FOODS.add(Food.FISH);
}
#Override
boolean isHappy() {
return isFoodOk(FAVORITE_FOODS);
}
}
If the answer will be A I will have another question.
NOTE: I edited the code because there was a silly mistake there - of course FAVORITE_FOODS should be declared in BullDog, not Dog. But that does not answer the question.
I would say none, since in all the approaches the Set<Food> is marked as static final thus the same set will be shared among all the instances of Dog class. Also, by declaring the Set as static final doesn't mean its contents cannot be modified, so in fact any client of Dog class or any subclass may add new Food or even clear it and all the Dogs will be affected.
This approach could do:
public abstract class Dog {
//this field should be final only so the variable cannot be modified
protected final Set<Food> favoriteFood;
protected Dog(Food ... food) {
//now the Set cannot be modified as well
favoriteFood = Collections.unmodifiableSet(new HashSet<Food>(Arrays.asList(food)));
}
//no need to be abstract, and clients cannot modify this set
public Set<Food> getFavoriteFoods() {
//I would recommend returning a new set that
return favoriteFood;
}
//You need to check if the dog likes the food to see if its ok
public boolean isFoodOk(Food food){
//not sure if your requirement is that it always should compare with CHICKEN, really odd...
return getFavoriteFoods().contains(food); //Food.CHICKEN);
}
//IMO this method needs a complete redesign, since I don't know the details I can't provide a solution =\
//at most it can be an abstract method and let each dog subclass implement it
public abstract boolean isHappy();
//boolean isHappy(){
// return isFoodOk();
//}
}
public class BullDog extends Dog {
public BullDog() {
super(Food.CHICKEN, Food.FISH);
}
#Override
public boolean isHappy() {
//define how the bulldog is happy
return ...;
}
}
You'll get a very realistic model of the world: all dogs will be happy, no matter what food is available.
Seriously: neither A nor B are good, because the FAVORITE_FOOD is a class attribute of the abstract Dog class. It would make some sense to have it as class attribute per race. Or, more realistic, as instance attribute for each individual dog.
What is specific for Dog types is favourite foods. So they need to answer the question 'what is your favourite food?' with the implementation of getFavoriteFoods. Being happy is not a question to ask to all Dog types differently. So A is better, in my opinion.