Better way to avoid casting? - java

I have interface Foo
public interface Foo {
public void test();
}
Class FooChild implements interface Foo.
public class FooChild implements Foo {
#Override
public void test() {...}
public void test2() {...}
}
I have to call function test2 in somewhere in the code.
Foo f = new FooChild();
((FooChild) f).test2();
I really hate casting an interface to a class.
So I added another interface Bar.
public interface Bar extends Foo {
public void test2();
}
public class FooChild implements Bar {
#Override
public void test() {...}
#Override
public void test2() {...}
}
Now I call test2() with casting to an interface, not a class.
Foo f = new FooChild();
((Bar) f).test2();
I may add function test2 to the interface Foo,
but there are too many classes that implement Foo.
If I add the function, I have to add codes to all the classes that implement Foo.
Although I can do that above, I actually don't have permission to edit Foo.
Will there be any fancier way to solve this problem? (hopefully without casting)
EDIT:
f is passed as a method parameter.
As Jon said, I should have be more specific.
Sorry for the confusion.
public void doSomething(Foo f) {
...
}

If you know that the variable value really has to be of type FooChild, just declare it that way:
FooChild f = new FooChild();
f.test2();
If there's some reason why that won't work for you, it's something you haven't told us...
EDIT: Okay, so apparently it's really a method parameter:
public void doSomething(Foo f) {
((FooChild) f).test2();
}
... so no, there's nothing you can do to avoid the cast. The cast indicates that there's a requirement on the value beyond what the declared variable type already guarantees - in this case, you want to say "It's got to actually be a FooChild, not just any implementation of Foo." Casts are the way of expressing that, if you can't change the parameter.

Bar f = new FooChild();
f.test2();

Hard to say what you exactly want here, but you could possibly create a helper function for any Foo objects to return a FooChild..
public FooChild getImpl(Foo input){
if (input instanceof FooChild){
return (FooChild)input;
}else{
return null;
}
}
that way you call your helper function like so (assuming not null:
getImpl(f).test2();
Note: this code does not check for nulls at all, which you would need to do in your code.

Related

How to nest methods in java to force user to use the nested name?

I'm writing a library, for more readability I want to force user to use nested methods to call the correct functions.
For example this is my class looks like:
public class Foo{
public void methodA(){}
public void methodB(){}
public void methodC(){}
}
What I'm expecting the user:
Foo foo = new Foo();
foo.methodA.methodB();
foo.methodA.methodC();
to call method B & C through calling the methodA as a prefix
After reading your question i think you are asking about Builder Design patten in which every methods return type is same class object and you can make call hierarchy like this.
obj.aMethod().bMethod().cMethod();
in your example just do like this:
public class Foo{
private static final Foo instance = new Foo();
private Foo(){}
public static Foo getInstance(){
return instance;
}
public Foo methodA(){
//Do stuff
return getInstance();
}
public Foo methodB(){}
public Foo methodC(){}
}
Now you can call like objfoo.getInstance().methodA().methodB();
Hope it will help you. To read more about that pattern
To force the user to use methodA to access methodB you could use an inner class.
In methodB you can access the Foo-Object with Foo.this.
public class Foo{
public Bar methodA()
{
// ...
return new Bar();
}
public class Bar {
private Bar() {}; // only methodA can create a Bar object
public void methodB(){}
public void methodC(){}
}
}
This is called as method chaining. You will need to set the return type of all methods as the same as the Class.
public class Foo{
public Foo methodA()
public Foo methodB()
public Foo methodC()
}
Now the client can simply call:
foo.methodA().methodB(), etc.
You can have one "terminal method" i.e. one that does not return a value. For example
public void methodD();
This method will be called last.
foo.methodA().methodB().methodC().method();
This line in itself will be valid as return type is void.
Please look at method chaining/ builder pattern YouTube videos, it will be clear.

How to override a method depending on a constructor?

Okay, so I'm not sure if this question already exists because I don't know how to format it, but here's the problem: can a same method produce different result depending on a constructor? (I apologize if I'm repeating the question or if it's a stupid question.)
For example, let's say that I have an interface MyInterface with function public void foo();. Let's say we have class:
public class MyClass implements MyInterface {
public MyClass() {
// I want foo() to print "Empty constructor" with sysout.
}
public MyClass(int x) {
// I want foo() to print "Constructor with int" with sysout.
}
}
So now, if create two references MyClass mc1 = new MyClass(); and MyClass mc2 = new MyClass(5); and then call mc1.foo(); and mc2.foo();, the result should be:
Empty constructor.
Constructor with int.
I tried with new MyInterface { #Override public void foo() { ... } } inside constructors but doesn't seem to work.
Yes. Store the variable and check it in the foo method.
public class MyClass implements MyInterface {
private int x;
public MyClass() {
// I want foo() to print "Empty constructor" with sysout.
}
public MyClass(int x) {
// I want foo() to print "Constructor with int" with sysout.
this.x = x;
}
public void foo(){
if(x > 0)
System.out.println("Constructor with int");
else
System.out.println("Empty constructor");
}
}
To answer the question: Not to my knowledge. Or at least not directly, you could start to read byte code and change it during run time, make it adapt-- so again, the answer is no.
Now the weird parts are the override and depending on constructor. It is not in the scope of overriding.
A method doing different things depending on the state of the Class is not too odd. However, making the method unique of how the class was instantiated I've never heard of. That being said, here is a fairly ugly solution to it.
public class Test
{
private final boolean intConstructorUsed;
public Test () {
intConstructorUsed = false;
}
public Test (int x) {
intConstructorUsed = true;
}
public void foo () {
if (intConstructorUsed == true) {
// do this
} else {
// do that
}
}
}
The foo method isn't that weird. The weird part is that you basically have to different implementations of foo depending on which constructor, you are sure you do not want an abstract class behind, with all shared methods except for one abstract void foo () that you override? Sure the classes will almost look identical, however they are not, as they do not share their foo ().
Yes, it's what's multiple constructors are designed to allow for - variation via object creation.
public class MyClass implements MyInterface {
private final String message;
public MyClass() {
message = "Empty constructor";
}
public MyClass(int x) {
message = "Constructor with int";
}
#Override
public void foo() {
System.out.println(message);
}
}
It's even threadsafe.
The thing to note here is that the implementation of the method is exactly the same, the variation is in the constructor. And it's the constructor which is called differently depending on what the caller wants to happen.

From Java to C# - Generic cast to BaseClass

i currently have a problem with generics. i want to transfer existing java code into c#. can anybody tell me, how i can do following in c# ?
For example i have a class named module with a generic parameter which inherits from basicdata. i want to add many of this objects to a handler so that they all can be updated in a single method.
in java i have something like this:
public class BasicData
{
}
public abstract class Modul<T extends BasicData>
{
T value;
abstract void update(); // do something with the value
}
public class Handler
{
LinkedList<Modul<?>> modulCollection = new LinkedList<Data<?>>();
void add(Modul<?> m)
{
this.dataCollection.add(m);
}
void update(){
for(Modul<?> d : this.modulCollection){
d.update();
}
}
}
the list should contain various modul-objects, where the value field itself can have various types but they all inherit BasicData.
i searched a while, but i only found exotic solutions. is there no easy way to do the similar thing in c#? i dont want to rewrite my whole design.
at first i thought i could declare the list like this in c#:
LinkedList<Modul<BasicData>> collection;
void add(Modul<BasicData> m)
{
this.dataCollection.add(m);
}
and then add the various objects like this:
class DataImpl : Modul<int>
{
}
handler.add(new DataImpl());
but i found out that you cannot cast this Modul.
is there a solution to do something like that?
thanks in advance,
mick
C# does not have the ? wildcard mechanics as Java has - What is the equivalent of Java wildcards in C# generics, so there is no direct native solution for this problem.
POSSIBLE SOLUTIONS:
1. Use base non-generic class or interface for your Modul:
public abstract class ModulBase : BasicData
{
abstract void update(); // do something with the value
}
public abstract class Modul<T> : ModulBase ...
or
public interface IUpdateable
{
void Update();
}
public abstract class Modul<T> : BasicData, IUpdateable...
And use it like:
public class Handler
{
LinkedList<IUpdateable> modulCollection = new LinkedList<IUpdateable>();
void add<T>(Modul<T> m) // It is generic now
{
this.dataCollection.add(m);
}
void update(){
foreach (IUpdateable d in this.modulCollection){
d.update();
}
}
}
Your Handler.moduelCollection is no longer generic with such an approach, but in any case(even in Java) you would not have been able to access different generics in a simple manner without casting - and that is not the best way to handle different datatypes put into one collection.
You could try the same in C# like below:
public abstract class Module<T> where T : BasicData
{
}
I think I got a solution for you. It kinda uses what others and you said and combines it with something not mention here.
If you have class Foo
class Foo {
public virtual void Method1() {
//Do something
}
public void Method2() {
//Do something
}
//class code
}
Now, you have a class Bar which inherits from Foo
class Bar : Foo {
public override void Method1() {
//Do something
}
public new void Method2() {
//Do something
}
//class code
}
If you declare a variable of the class Bar and try to convert it to Foo, it is completely acceptable and you don't loose any data. However, the next time you want to use the extra properties, methods and variables, you will need to convert it back to Bar. Though, if common members are an override, they should behave as if they were called by a Bar variable, otherwise, if the object is cloned or cast backwards, the common members should behave as if they were called by an Foo instance.
For example:
Bar myBar = new Bar();
Foo myFoo = myBar; //Now myFoo and myBar refer to the same memory address
Foo myFoo2 = myBar.Clone() as Foo; //myFoo2 and myBar do not refer to the same memory address
//These should do exactly the same thing because Method1 is an override
myBar.Method1();
myFoo.Method1();
//These should not do exactly the same thing unless Method2 was not changed in Bar
myBar.Method2();
myFoo.Method2();
//These should do exactly the same thing because Method1 is an override
myBar.Method1();
myFoo2.Method1();
//These should not do exactly the same thing unless Method2 was not changed in Bar
myBar.Method2();
myFoo2.Method2();
Bar myBarConvertedBack = (Bar)myFoo; //No data lost
Now back to the question. Try this:
public abstract class Module<T> where T : BasicData {
protected T value;
public abstract void Update();
public virtual T Value {
get;
set;
}
}
public class Handler
{
LinkedList<Modul<BasicData>> modulCollection = new LinkedList<Data<BasicData>>();
pulic void Add(Modul<BasicData> m)
{
this.modulCollection.add(m);
}
public void Update() {
foreach (Modul<BasicData> d in this.modulCollection)
d.update();
}
}
Consider this class as possible derived class from Module:
public class Class1: Module<BasicData> {
public Class1(BasicData val) {
base.value = val;
}
public override void Update() {
//Do something here
}
public override BasicData Value {
get {
return base.value;
}
set {
base.value = value;
}
}
}
Also see more cases in stackoverflow in the Related or Linked to this question if it is clear. Furthermore, if I'm wrong somewhere correct me

Warn developer to call `super.foo()` in java

Lets say I have these two classes, one extending the other
public class Bar{
public void foo(){
}
}
public class FooBar extends Bar {
#Override
public void foo(){
super.foo(); //<-- Line in question
}
}
What I want to do is warn the user to call the super-class's method foo if they haven't in the override method, is this possible?
Or is there a way to know, using reflection that a method that overrides a method of its super-class calls the original method if I pass on the class type to the super?
for example:
public abstract class Bar{
public Bar(Class<? extends Bar> cls){
Object instance = getInstance();
if (!instance.getClass().equals(cls)) {
throw new EntityException("The instance given does not match the class given.");
}
//Find the method here if it has been overriden then throw an exception
//If the super method isn't being called in that method
}
public abstract Object getInstance();
public void foo(){
}
}
public class FooBar extends Bar {
public FooBar(){
super(FooBar.class);
}
#Override
public Object getInstance(){
return this;
}
#Override
public void foo(){
super.foo();
}
}
Maybe even an annotation I can put on the super method so it shows that it needs to be called?
EDIT
Note, its not the super class that needs to call the foo method, it would be someone calling the sub class's foo method, for example a database close method
I would even be happy with making the method "un-overrideable" if it came down to it, but would still like to give it a custom message.
Edit 2
This here is what I wanted in a way:
But it would still be nice to have the above, or even give them a custom message to do something else like, Cannot override the final method from Bar, please call it from your implementation of the method instead
EDIT: To answer the edited, question, which includes:
I would even be happy with making the method "un-overrideable"
... just make the method final. That will prevent subclasses from overriding it. From section 8.4.3.3 of the JLS:
A method can be declared final to prevent subclasses from overriding or hiding it.
It is a compile-time error to attempt to override or hide a final method.
To answer the original question, consider using the template method pattern instead:
public abstract class Bar {
public foo() {
// Do unconditional things...
...
// Now subclass-specific things
fooImpl();
}
protected void fooImpl();
}
public class FooBar extends Bar {
#Override protected void fooImpl() {
// ...
}
}
That doesn't force subclasses of FooBar to override fooImpl and call super.fooImpl() of course - but FooBar could do this by applying the same pattern again - making its own fooImpl implementation final, and introducing a new protected abstract method.
what you could do is something like following
public class Bar{
public final void foo(){
//do mandatory stuff
customizeFoo();
}
public void customizeFoo(){
}
}
public class FooBar extends Bar {
#Override
public void customizeFoo(){
//do custom suff
}
}
foo method made 'final' in superclass so that subclasses can't override and avoid doing mandatory stuff

Interface questions

Suppose that I have interface MyInterface and 2 classes A, B which implement MyInterface.
I declared 2 objects: MyInterface a = new A() , and MyInterface b = new B().
When I try to pass to a function - function doSomething(A a){} I am getting an error.
This is my code:
public interface MyInterface {}
public class A implements MyInterface{}
public class B implements MyInterface{}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
test(b);
}
public static void test(A a){
System.out.println("A");
}
public static void test(B b){
System.out.println("B");
}
}
My problem is that I am getting from some component interface which can be all sorts of classes and I need to write function for each class.
So one way is to get interface and to check which type is it. (instance of A)
I would like to know how others deal with this problem??
Thx
Can you not just have a method on the interface which each class implements? Or do you not have control of the interface?
This would provide both polymorphism and avoid the need to define any external methods. I believe this is the intention of an interface, it allows a client to treat all classes implementing it in a non type specific manner.
If you cannot add to the interface then you would be best introducing a second interface with the appropriate method. If you cannot edit either the interface or the classes then you need a method which has the interface as a parameter and then check for the concrete class. However this should be a last resort and rather subverts the use of the interface and ties the method to all the implementations.
It sounds like you are after something like this:
public static void test(MyInterface obj){
if(obj instanceof A) {
A tmp = (A)obj;
} else if(obj instanceof B) {
B tmp = (B)obj;
} else {
//handle error condition
}
}
But please note this is very bad form and indicates something has gone seriously wrong in your design. If you don't have control of the interface then, as suggested by marcj, adding a second interface might be the way to go. Note you can do this whilst preserving binary compatibility.
I'm unclear on what you're actually asking, but the problem is that you don't have a method that takes a parameter of type MyInterface. I don't know what the exact syntax is in Java, but you could do something like if (b is B) { test(b as B) } but I wouldn't. If you need it to be generic, then use the MyInterface type as the variable type, otherwise use B as the variable type. You're defeating the purpose of using the interface.
I'm not sure if I fully understand the issue, but it seems like one way might be to move the test() methods into the child classes:
public interface MyInterface {
public void test();
}
public class A implements MyInterface{
public void test() {
System.out.println("A");
}
}
public class B implements MyInterface{
public void test() {
System.out.println("B");
}
}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
b.test();
}
}
You could similarly use a toString() method and print the result of that. I can't quite tell from the question, though, if your requirements make this impossible.
I think visitor design pattern will help you out here. The basic idea is to have your classes (A and B) call the appropriate method themselves instead of you trying to decide which method to call. Being a C# guy I hope my Java works:
public interface Visitable {
void accept(Tester tester)
}
public interface MyInterface implements Visitable {
}
public class A implements MyInterface{
public void accept(Tester tester){
tester.test(this);
}
}
public class B implements MyInterface{
public void accept(Tester tester){
tester.test(this);
}
}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
a.accept(this);
b.accept(this);
}
public void test(A a){
System.out.println("A");
}
public void test(B b){
System.out.println("B");
}
}
Use only one public class/interface in one .java file, otherwise it'll throw error. And call the object with the object name.. You declared two methos in Teater class only, then what the purpose of declaring class A,B.
I usually use an abstract class to get around this problem, like so:
public abstract class Parent {}
public class A extends Parent {...}
public class B extends Parent {...}
That allows you to pass Parent objects to functions that take A or B.
You have 3 options:
Visitor pattern; you'll need to be able to change the MyInterface type to include a method visit(Visitor) where the Visitor class contains lots of methods for visiting each subclass.
Use if-else inside your method test(MyInterface) to check between them
Use chaining. That is, declare handlers ATester, BTester etc, all of which implement the interface ITester which has the method test(MyInterface). Then in the ATester, check that the type is equal to A before doing stuff. Then your main Tester class can have a chain of these testers and pass each MyInterface instance down the chain, until it reaches an ITester which can handle it. This is basically turning the if-else block from 2 into separate classes.
Personally I would go for 2 in most situations. Java lacks true object-orientation. Deal with it! Coming up with various ways around it usually just makes for difficult-to-follow code.
Sounds like you need either a) to leverage polymorphism by putting method on MyInterface and implementing in A and B or b) some combination of Composite and Visitor design pattern. I'd start with a) and head towards b) when things get unwieldy.
My extensive thoughts on Visitor:
http://tech.puredanger.com/2007/07/16/visitor/
public interface MyInterface {}
public class A implements MyInterface{}
public class B implements MyInterface{}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
test(b); // this is wrong
}
public static void test(A a){
System.out.println("A");
}
public static void test(B b){
System.out.println("B");
}
}
You are trying to pass an object referenced by MyInterface reference variable to a method defined with an argument with its sub type like test(B b). Compiler complains here because the MyInterface reference variable can reference any object which is a sub type of MyInterface, but not necessarily an object of B.There can be runtime errors if this is allowed in Java. Take an example which will make the concept clearer for you. I have modified your code for class B and added a method.
public class B implements MyInterface {
public void onlyBCanInvokeThis() {}
}
Now just alter the test(B b) method like below :
public static void test(B b){
b.onlyBCanInvokeThis();
System.out.println("B");
}
This code will blow up at runtime if allowed by compiler:
MyInterface a = new A();
// since a is of type A. invoking onlyBCanInvokeThis()
// inside test() method on a will throw exception.
test(a);
To prevent this, compiler disallows such method invocation techniques with super class reference.
I'm not sure what are you trying to achieve but it seems like you want to achieve runtime polymorphism. To achieve that you need to declare a method in your MyInterface and implement it in each of the subclass. This way the call to the method will be resolved at run time based on the object type and not on the reference type.
public interface MyInterface {
public void test();
}
public class A implements MyInterface{
public void test() {
System.out.println("A");
}
}
public class B implements MyInterface{
public void test() {
System.out.println("B");
}
}
public class Tester {
public static void main(String[] args){
MyInterface a = new A();
MyInterface b = new B();
b.test(); // calls B's implementation of test()
}
}

Categories