Runtime determination of base class at runtime in Java - java

I have two classes, one which is hardware-dependent and one which is not (let's call them HardwareDependent and HardwareIndependent respectively). The Hardware dependent class extends the hardware independent class. Now I have another class which at least must be an extension of the HardwareIndependent, but I would prefer it to be an extension of HardwareDependent when possible so it may leverage the additional functionality. Is there a possibility of using reflection or something else to accomplish this? Or is this a total technical impossibility? I suppose if all else fails, I could write the class twice, but it seems to me that is an ineffective approach. Thanks for any help in advance.

Inheritance is fixed at compile time.
It sounds like you don't want your new class to extend HardwareIndependent or HardwareDependent; you want it to use an object which could be either. You want composition and not inheritance. You're third class (we'll call it HardwareComposite) has a reference to a HardwareIndependent. Then, you can check if it is HardwareDependent at runtime with the instanceof operator, and if so cast it to HardwareDependent and use the additional facilities that provides.
If your design is forcing you to mix concepts of inheritance and composition, you might look into the Facade and Factory patterns.

Related

Java extends programmatically

I am wondering about replacing Java's 'extends' keyword somehow for dynamically extending a class based on a parameter(file, environment variable, db...basically anything). Is this even possible because playing with class loaders or calling constructors does not achieve this. I am not asking "should I use interface or superclass hierarchy" rather what is extending really mean under the hood in JAVA because there aren't any good description about it just the good old inheritance jargon:
https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
The only way to "replace the extends keyword" is to dynamically create classes at runtime, which is entirely possible but non-trivial. Vert.x is a good example of a project that makes extensive use of dynamically-generated classes.
Java wasn't designed as a dynamic language in that sense. There are several dynamic languages out there (some of which can run on the JVM), such as JavaScript.
rather what is extending really mean under the hood...
Without getting into a long treatise on OOP, when you say Derived extends Base, it means that Derived inherits both the public and protected API of Base (which it can then add to) and also the implementation of that API. It means that code expecting to see a Base instance can accept a Derived instance, because Derived "is a" Base. This link is created a compile-time. At runtime, instantiating an instance of Derived involves all of the plumbing that instantiating a Base instance involves, plus then the added plumbing for Derived.
To achieve this you need to maintain various versions of a class based on the condition and you have to customise class loader as well because at a point when you find that you have to load a particular instance, you need to load that class which is not loaded by default class loader on JVM startup.
Its better to maintain multiple versions of the class and let JVM do its job which it does perfectly.
You can't do that with a language like Java. The information about "inheritance" is not only used by the compiler, it is also "hard-baked" into the compiled byte code.
If you really want to such kind of "dynamic" meta programming; you are better of using languages that allow you to do so; instead of "violating" a language that was never intended for such kind of usage.
To use some stupid comparison: just because you happen to know "screws" and "hammer" ... you wouldn't start to use a hammer to get those screws into the wall, would you? Instead, you would be looking for a tool that works better with "screws" than a hammer.
If you still want your code to run within a JVM; you might consider languages like jython or jruby.

Build a Separate Java Class Hierarchy

Every other class in Java inherits from the Object class.
Is it possible to add a second, completely separate, class hierarchy in Java based around my own FastObject class?
My original goal in doing so was to create smaller, faster objects with less functionality specifically designed for certain algorithms. But let me be clear, I am not interested in whether or not this is a "good idea". I just want to know if it is possible; I have not been able to find a way to do so. Would it require a change to the JVM? New boot classpath functionality? Is the real solution to ignore Object and look at replacing java.lang.Class? Would using a direct Java compiler instead of a VM make my job any easier?
To be clear, I don't just want to edit the root Object class. That would require potentially re-writing the entire Java library. I don't want to replace the current hierarchy, I just want to create a separate one I can use in the same code.
No, this is not possible.
All created classes extend another class, either explicitly or implicitly. If you create a class and explicitly define which class it extends, then it extends that class. If not, then it implicitly extends Object. There is no way around this, just as there is no way to overload operators or anything of that sort. It is a fundamental design decision of the Java programming language.
All classes extend Object. The only things that don't are primitive types. The exception to this is Object itself, of course, which does not extend itself.
It may be possible for you to inject your own Object implementation by mucking with the boot classpath. However, I don't think there is any way to use a base object other than Object. You could try some byte code manipulation, but it is entirely possible that your modified class will be rejected by the class loader.

Naming convention for interface / class / mockClass in Java?

I'm creating a mock class for a Lexer object, and I think I may need to do some refactoring. I have two options:
Create an interface Lexer, and rename the current Lexer to something like RealLexer. Have MockLexer implement Lexer, and method calls take anything of type Lexer. I dislike that my precious Lexer class is now renamed to something that has no meaning if you don't know that there's a mock class.
Create an interface LexerInterface (which I already dislike, since it has Interface in its name), but allowing myself to keep the current Lexer the way it is. MockLexer then implements LexerInterface. Another downside is that method calls take LexerInterface as params.
Both options smell bad to me, so I figured I'd let standards decide for me. Has anyone had experience with this?
I'd definitely vote for using Lexer as your interface name. How about adding some information about how or why your implementation does its thing as part of the name?
E.g.:
StringParsingLexer
TokenizingLexer
SingleThreadedLexer
{ThirdPartyLibraryName}DelegatingLexer
Also, do you really need to be explicitly constructing a MockLexer? Using a framework like Mockito can make your testing considerably easier and faster; You can get started as easily as:
Lexer mockLexer = Mockito.mock(Lexer.class);
Mockito.when(mockLexer.doFoo()).thenReturn("bar");
My recommendation, as I stated in the comments, is to use Lexer for your interface and DefaultLexer for the default implementation. This pattern is used quite frequently and as such is very understandable to anyone who will be maintaining your code. As for the mock object, it would also be understandable to name this something like MockLexer.
As an example of a naming convention that Java uses:
javax.swing.table.TableModel is an interface
javax.swing.table.AbstractTableModel is an abstract class implementing TableModel
javax.swing.table.DefaultTableModel is an implementation of AbstractTableModel.
There is however, no recommendation in the Java Codding Conventions outside of using capital letters, nouns, etc.
I usually use option 1 - interfaces called Lexer, with default implementations called either DefaultLexer or LexerImpl. I like this, because I think it lets you talk about the classes easily - if you have multiple implementations of Lexers, then their concrete names can describe the implementation type - eg NativeLexer or TreeBasedLexer or whatever. As a commenter mentioned, then your mock class (if you have one) can follow this pattern with a name like MockLexer.
However, with mocking libraries such as the excellent Mockito, you can mock concrete classes anyway - so you no longer need to use interfaces everywhere in order to test things easily. Here is the example they give in their documentation:
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
That said, I would still recommend using interfaces instead of tying method signatures to concrete classes, because then things that use Lexer do not need to be tied to the implementation - this can be a massive gain in maintainability (eg if you need to have multiple implementations later).
In my experience there are two standards.
"Tag" your interface. (ILexer, LexerInterface, etc)
Use the name for your interface and use a different name for the concrete implementation.
I know these are already the options you presented. The trouble is, not one of them is firmly the "standard."
I strongly prefer option 2). A class name for an object should tend to be a noun that fits within the context of an "is-a" sentence. It feels weird to say that an object "is-a" LexerInterface whereas it is natural to say that an object "is-a" DefaultLexer.
Since ultimately my class or interface name represents a type, I shy away from "meta" information in a class or interface name.

Why make Abstract classes and Interfaces?

Well I was going to ask what the difference is but it's been answered before. But now I'm asking why did they make these differences? (I'm speaking about java here, I don't know if the same applies to other languages)
The two things seem very similar. Abstract classes can define a method body whilst interfaces can't, but multiple interfaces can be inherited. So why didn't they (by 'they' I mean Sun when they wrote Java) make one thing where you can write a method body and this type can be inherited more than once by a class.
Is there some advantage in not being able to write a method body, or extend multiple times that I'm not seeing?
Because allowing classes to inherit multiple implementations for the same method signature leads to the obvious question, which one should be used at runtime.
Java avoids this by supporting multiple inheritance only for interfaces. The signatures declared in each interface can be combined much more easily (Java basically uses the union of all methods)
Multiple inheritance in C++ leads to semantic ambiguities like the diamond inheritance problem. MI is quite powerful, but has complex consequences.
Making interfaces a special case also raises the visibility of the concept as a means of information hiding and reducing program complexity. In C++, defining pure abstract bases is a sign of a mature programmer. In Java, you encounter them at a much earlier stage in the evolution of a programmer.
Multiple inheritance is more difficult to implement in a language (compiler really) as it can lead to certain issues. These issues have been discussed here before: What is the exact problem with multiple inheritance.
I've always assumed this was a compromise in Java. Interfaces allow a class to fulfill multiple contracts without the headache of multiple inheritance.
Consider this example:
public abstract class Engine
{
public abstract void switchPowerOn();
public abstract void sprinkleSomeFuel();
public abstract void ignite();
public final void start()
{
switchPowerOn();
sprinkleSomeFuel();
ignite();
}
}
Abstract class can help you with having solid base methods which can or cannot be overriden, but in these methods it uses abstract methos to provide you an opportunity to do your specific thing. In my example different engines have different implementations of how they switch power on, sprinkling some fuel for the ignition, and doing the ignition, however the starting sequence of the engine stays always the same.
That pattern is called "Form Template Method" and is quite frankly the only sensible usage of abstract classes in Java for me.
Making them one thing is the route that the Scala guys took with Traits which is an interface that can have methods and supports multiple inheritance.
I think interfaces, for me, are clean in that they only specify requirements (design by contract) whereas abstract classes define common behaviour (implementation), so a different tool for a different job? Interfaces probably allow more efficient code generation during compile time as well?
The other approach you are describing is the approach used by C++ (mixins for example). The issues related to such "multiple inheritance" are quite complex, and has several critics in C++.
Inheritance means you inherit the nature (meaning) and responsibility (behaviour) of the parent class, while interface implementation means you fulfill a contract (e.g. Serializable), which may have nothing to do with the core nature or responsibility of the class.
Abstract class let you define a nature that you want to be generic and not directly instanciable, because it must be specialized. You know how to perform some high-level tasks (e.g. make a decision according to some parameters), but you don't know the details for some lower-level actions (e.g. compute some intermediary parameters), because it depends on implementation choices. An alternative for solving this problem is the Strategy design pattern. It is more flexible, allowing run-time strategy switching and Null behaviour, yet it is more complex (and runtime swtiching is not always necessary). Moreover, you might lose some meaning & typing facilities (polymorphism & type-checking becomes a bit harder because the Strategy is a component, not the object itself).
Abstract class = is-a, Strategy = has-a
Edit: as for multiple inheritance, see Pontus Gagge's answer.

Coding to interfaces? [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 9 years ago.
I want to solidify my understanding of the "coding to interface" concept. As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes. To use the interface one can simply call the methods on an instance of the concrete class.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Based on the above:
Are there any fallacies in my understanding of "coding to interfaces"?
Are there any benefits of coding to interfaces that I missed?
Thanks.
Just one possible correction:
To use the interface one can simply call the methods on an instance of the concrete class.
One would call the methods on a reference of the type interface, which happens to use the concrete class as implementation:
List<String> l = new ArrayList<String>();
l.add("foo");
l.add("bar");
If you decided to switch to another List implementation, the client code works without change:
List<String> l = new LinkedList<String>();
This is especially useful for hiding implementation details, auto generating proxies, etc.
You'll find that frameworks like spring and guice encourage programming to an interface. It's the basis for ideas like aspect-oriented programming, auto generated proxies for transaction management, etc.
Your understanding seems to be right on. Your co-worker just swung by your desk and has all the latest pics of the christmas party starring your drunk boss loaded onto his thumbdrive. Your co-worker and you do not think twice about how this thumbdrive works, to you its a black box but you know it works because of the USB interface.
It doesn't matter whether it's a SanDisk or a Titanium (not even sure that is a brand), size / color don't matter either. In fact, the only thing that matters is that it is not broken (readable) and that it plugs into USB.
Your USB thumbdrive abides by a contract, it is essentially an interface. One can assume it fulfills some very basic duties:
Plugs into USB
Abides by the contract method CopyDataTo:
public Interface IUSB {
void CopyDataTo(string somePath); //used to copy data from the thumbnail drive to...
}
Abides by the contract method CopyDataFrom:
public Interface IUSB {
void CopyDataFrom(); //used to copy data from your PC to the thumbnail drive
}
Ok maybe not those methods but the IUSB interface is just a contract that the thumbnail drive vendors have to abide by to ensure functionality across various platforms / vendors. So SanDisk makes their thumbdrive by the interface:
public class SanDiskUSB : IUSB
{
//todo: define methods of the interface here
}
Ari, I think you already have a solid understanding (from what it sounds like) about how interfaces work.
The main advantage is that the use of an interface loosely couples a class with it's dependencies. You can then change a class, or implement a new concrete interface implementation without ever having to change the classes which depend on it.
To use the interface one can simply call the methods on an instance of the concrete class.
Typically you would have a variable typed to the interface type, thus allowing only access to the methods defined in the interface.
The obvious benefit is knowing of the functionality provided by the concrete class, irrespective of its specific implementation.
Sort of. Most importantly, it allows you to write APIs that take parameters with interface types. Users of the API can then pass in their own classes (which implement those interfaces) and you code will work on those classes even though they didn't exist yet when it was written (such as java.util.Arrays.sort() being able to sort anything that implements Comparable or comes with a suitable Comparator).
From a design perspective, interfaces allow/enforce a clear separation between API contracts and implementation details.
The aim of coding against interfaces is to decouple your code from the concrete implementation in use. That is, your code will not make assumptions about the concrete type, only the interface. Consequently, the concrete implementation can be exchanged without needing to adjust your code.
You didn't list the part about how you get an implementation of the interface, which is important. If you explicitly instantiate the implementing class with a constructor then your code is tied to that implementation. You can use a factory to get an instance for you but then you're as tied to the factory as you were before to the implementing class. Your third alternative is to use dependency injection, which is having a factory plug the implementing object into the object that uses it, in which case you escape having the class that uses the object being tied to the implementing class or to a factory.
I think you may have hinted at this, but I believe one of the biggest benefits of coding to an interface is that you are breaking dependency on concrete implementation. You can achieve loose coupling and make it easier to switch out specific implementations without changing much code. If you are just learning, I would take a look at various design patterns and how they solve problems by coding to interfaces. Reading the book Head First: Design Patterns really helped things click for me.
As I understand it, one creates interfaces to delineate expected functionality, and then implements these "contracts" in concrete classes.
The only sort of mutation i see in your thinking is this - You're going to call out expected contracts, not expected functionality. The functionality is implemented in the concrete classes. The interface only states that you will be able to call something that implements the interface with the expected method signatures. Functionality is hidden from the calling object.
This will allow you to stretch your thinking into polymorphism as follows.
SoundMaker sm = new Duck();<br/>
SoundMaker sm1 = new ThunderousCloud();
sm.makeSound(); // quack, calls all sorts of stuff like larynx, etc.<br/>
sm1.makeSound(); // BOOM!, completely different operations here...

Categories