Call super make must be first statement in method [closed] - java

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.
}
}

Related

How to create a function that cannot be executed by a constructor? [closed]

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
Say I have function x which is a function in an abstract class. x adds itself to a private arraylist if it does not already contain it. I want to make a function that cannot be executed inside the constructor so that 'x' cannot be added to the arraylist if the constructor errors, and can only be called after the constructor(s) has finished. The gist of my situation is that I want the set to be private so only the class A can access it, nothing should ever be removed from the list if it is added, the addToArray function should only ever need to happen once and should never happen from the constructor. The constructor would only matter if it is a subclass' constructor.
public abstract class A {
public A () {
//do stuff :)
}
public abstract void doStuff();
public final void addToArray() {
if(isCalledFromConstructor/*HELP ME HERE*/)
throw new RuntimeException("Cannot execute addToArray function from a constructor");
if(!AS.contains(this))AS.add(this);
}
private static final java.util.Set<A> AS = new java.util.concurrent.ConcurrentSkipListSet<A>();
public static final class B extends A {
public B(){
addToArray();//THROW AN ERROR HERE
}
#Override
public void doStuff(){
System.out.println("Doing stuff");
}
}
}
With more context on what you’re trying to accomplish, I might be able to give a better suggestion on achieving your ultimate goal. That said, if you are absolutely set on doing what you are asking, one way is to call
Thread.currentThread().getStackTrace()
from within addToArray and examine the contents of the stack trace to see if you’re currently inside of a constructor.
In particular this
boolean isCalledFromConstructor() {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
String methodName = stackTraceElement.getMethodName();
if (methodName.equals("<init>")) return true;
}
return false;
}
should do it for you, although it's not my favorite bit of code :)
As other people have commented, doing this may be a sign of a design oversight. Please give more details on the big picture goal if you can.
You could have a private variable like boolean isInitialized and set this to true in constructor. In the add method check if this value is false and throw error.
If your environment allows it you could use #PostConstruct method annotation to add it to your list safely.
But i also recommend to check your code design. You are adding an instance to a private static list that is not thread safe.

Getting my head around implementations [closed]

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.

Java subclass methods are not overriding despite explicit use of #Override [closed]

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"; }
}

robot scenario - java inheritance, interface types and abstract classes [closed]

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);
}
}

How to check a method executed in the unit test context? [closed]

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 9 years ago.
Improve this question
I am trying to add some features to the legacy libraries and plan to make it testable.
I want to limit some methods allowed call in the testing context, like change the global system configurations. Because some changes are dangerous for production, to limit the accessablitiy is important.
I use the junit4 to test my project, any suggestions for it?
class Foo {
public void methodA() {
// is it possible limit methodA only allowed invoked by JUNIT ?
}
}
I would make a stub
Lib l = new Lib() {
#Override
void xxx() {
Assert.fail("calling xxx() is not allowed");
}
};
The thing comes in my mind is to use dependency injection to use two different implementations of the same interface, one for production and one for testing. The one you inject in the production execution could just have empty method that doesn't actually do nothing. Concept:
class Foo {
private Bar bar;
public Foo() {
bar = new DefultBarImplementation();
}
public setBar(Bar bar) {
this.bar = bar;
}
//use bar in your other methods
}
In your tests
Foo foo = new Foo();
foo.setBar(new TestBarImplementation());
You can make the methods package-private and have the tests in the same package.
public class Foo{
public void publicMethod();
void forTestingOnly();
}

Categories