Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make an abstract algorithm class for informed search with different heuristics. My idea was to have different subclasses overwrite the default heuristic() method, but the dynamic binding seems not to be working when I call the subclasses.
In astar.java:
public interface Astar {
abstract String heuristic();
}
In search.java
public class Search implements Astar {
public String heuristic() { return "default heuristic"; }
}
In EuclidianSearch.java:
public class EuclidianSearch extends Search {
#Override
public String heuristic() { return "Euclidian"; }
}
In ChebyshevSearch.java:
public class ChebyshevSearch extends Search {
#Override
public String heuristic() { return "Chebyshev"; }
}
In main.java:
EuclidianSearch e_search = null; ChebyshevDistance ch_search = null;
Search[] SearchObjects = {e_search, ch_search};
for(Search so : SearchObjects) {
System.out.println(so.heuristic());
}
When run, it displays:
default heuristic
default heuristic
I define the array in terms of Search so I can be flexible: eventually, I want to have five or more different heuristics. Why doesn't the heuristic() method of the subclass override that of the superclass?
You will get NullPointerException for calling so.heuristic() because you don't instance class, use these codes :
EuclidianSearch e_search = new EuclidianSearch();
ChebyshevDistance ch_search = new ChebyshevDistance();
but it is not sufficient to solve you problem, you should implement AStart interface by diffrent classes. don't forget that a class which implement a interface should implement all interface method. otherwise, you should define an abstract class to define only some methods and override remain methods in other classes with extend you previous class.
public class Search implements Astar {
#Override
public String heuristic() { return "default heuristic"; }
}
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 5 months ago.
Improve this question
This is related to Java Strategy design pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.
I have common code logic to be executed for all the strategies which is have implemented using Java Strategy design pattern. Which is the right place to write this common logics(something like validations and other stuffs).
Consider the below code. Here I want to do file validation which is common across any file type . Something like , the file should exist and its size should be greater than zero and file name validation. All these file related common stuff I want to keep in some place. Which could be a right design for this?
//BaseFileParser.java
public abstract class BaseFileParser{
public abstract void parseFile();
}
//XMLFileParser.java
public class XMLFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing an XML file goes here
}
}
//CSVFileParser.java
public class CSVFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing a CSV file goes here
}
}
//Client.java
public class Client{
private BaseFileParser baseFileParser;
public Client(BaseFileParser baseFileParser){
this.baseFileParser=baseFileParser;
}
public void parseFile(){
baseFileParser.parseFile();
}
public static void main(String args[]){
//Lets say the client needs to parse an XML file
//The file type(XML/CSV) can also be taken as
//input from command line args[]
Client client=new Client(new XMLFileParser());
client.parseFile();
}
}
If you have common behaviour, then abstract class or class is what we can use. So basic idea is to put common logic into some base common strategy class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete strategy.
I am sorry, I am not Java guy, but I've provided comments how it can be implemented in Java. Let me show an example via C#.
This is our abstract class which has common strategy:
public abstract class BaseStrategy
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{ }
public abstract void
UnCommonBehaviourHereShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
UPDATE:
This is your abstract class:
public abstract class BaseFileParser
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public bool IsValid()
{
return true;
}
public abstract void ParseFile();
}
and its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}
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 2 years ago.
Improve this question
If inherited method does not contain a call to super in first statement, I need a compile error, requires constructor-like behavior. Is it possible to do this?
public class ModelBase {
protected int defaultCount;
public void init() {
defaultCount = 10;
}
}
public class Model extends ModelBase {
#Override
public void init() {
System.out.println(defaultCount);
super.init();//need error or notification
}
}
Note that requiring a call to super at all is considered an anti-pattern, in part because there is no way to enforce it, or to enforce that it is called at the right point in the method etc.
One way to do this with plain Java is not to require a call to super at all, but rather to provide a non-overrideable method which calls a subclass-specific method at the right time.
For example:
class YourClass {
final void yourMethod() {
// Stuff you want to happen first.
// and then at the end, call
subclassSpecific();
}
protected void subclassSpecific() {}
}
Now, subclasses can override that method to provide specific behavior that will occur after the rest of the things in yourMethod:
class YourSubclass extends YourClass {
#Override protected void subclassSpecific() {
// Whatever.
}
}
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