Overriding a class method in subclass Java - java

I have a class which has 2 methods:
class A {
public methodA();
public methodB();
}
I have two other classes B & C, which have Class A as its members:
class B {
A a;
B(Config config) {
a = config.getA();
}
}
class C {
A a;
C(Config config) {
a = config.getA();
}
}
However, in class C I want to implement a different way of method B. I guess I need to override the method, but then I will need to make class A as an abstract class. Is that correct? Is there a different way to approach this
Edit: I am not directly creating a new instance of A. I am getting it from a helper class.

I will need to make class A as an abstract class
No just make sure that methodB has not been declared to be final, since final methods cannot be overridden. You can override the method "inline" by creating a new anonymous class from the A class within your C code:
class C {
A a;
C() {
a = new A() {
#Override
public void methodB() {
// .... code goes here
}
};
}
}

Can't be done in simple way.
In Java, if you need method to be overriden, it is done in a child class. However as you get the instance of A from someone else (the config), you have no way to control what is the class instantiated by config.
There are some alternatives:
If the new methodB can be done without knowing the internal of A, you can create a wrapper of A:
class C {
static class CustomA extends A{
A a;
public CustomA (A a) { this.a = a; }
#Override
public void methodB() {
a.methodB();
a.otherMethod();
}
}
A a;
C(Config config) {
a = new CustomA(config.getA());
}
}
Another alternatives is to change your Config to allow creation of other A child classes dictated by the caller of getA(). This can be done by misc way like Reflection or initialization of already-created A instance, and etc.
Another alternative is to extract logic of methodB out to a strategy. So you can replace the strategy to whatever you want. Check out Strategy pattern in GoF design pattern.

Related

Parent class function access in Java

I have two child classes B and C which inherit from one parent class A. Is it possible that I can make certain functions of class A accessible in B but not in C in java?
Well i don't know a way to forbid it in the Code. But you could just override and then don'f fill them.
If what you want is to forbid to call destroyEverything() from class C:
public class A {
public void travel() {
System.out.println("Travel from A");
}
public void makePee() {
System.out.println("Call from A");
}
}
public class B extends A {
public void travel() {
super.travel();
System.out.println("Travel from B");
}
public void makePee() {
super.makePee();
System.out.println("Call from B");
}
}
Then, on C:
public class C extends A {
public void travel() {
super.travel();
System.out.println("Travel from C");
}
public void makePee(){
throw new UnsupportedOperationException("Not supported from C");
}
}
BUT, if what you want is to not inherit stuff from A, it is probably a flaw at the design of your class hierarchy and class C should not inherit from A.
Example of design flaw: Class A is Animal, class B is Beaver, and you want your class C Cadillac to inherit stuff from Animal since Animal already has the method travel.
Since maybe you don't want to inherit the method makePee (every animal urinates, but Cadillacs don't), it is better to move Cadillacs (class C) to another class hierarchy or find another class design
As per my thinking it is not possible.
Let's see the one real time example->
A Parent have a two child then both are able to access parent property .it is there no restriction on that you can not use this or you can not use this.
And if you want to do like that then you can implicitly write logic in B class also

Changing a class variables type

I have two different interfaces which employ the same methods but dont implement or extend each other. These two interfaces are each extended by another class which implements the interfaces methods
I then have a class which is located in a seperate package which calls the interface methods.
So the class has methods which calls the methods of the interfaces, which are all the same.
public void doThis(){
connection.doThis();
}
public void doThat(){
connection.doThat();
}
public void doAnother(){
connection.doAnother();
}
Now, i want to make the variable connection work for both interface1 and interface2.
My idea was to set connection as a class variable
Object connection
and then to change it type to interface1 or interface2 depending on a condition:
if(this){
//condition which converts connection to type interface1
}
else{
//condition which converts connection to type interface2
}
How do i do this. Can i do this?
I have been given an interface which can not be changed, yet does not implement remote. But my project uses RMI. So i created a 2nd interface in a seperate package which implemets Remote. Thus the reason for 2 different interfaces that do he same thing.
I think it would be easier to make the class containing the method 'connection' public, as it would be accessible from all packages.
This seems like a really weird setup, but I won't question you.
If you know the condition at the method call site (eg, the condition is a constant flag passed to the method), you could parameterize the method with a generic instead. For example:
public class TestGenerics {
public static interface A {
public void a();
}
public static interface B {
public void a();
}
public static class C implements A, B {
public void a() {
System.out.println("a");
}
}
public static <T> T getCAsT() {
return (T) new C();
}
public static void main(String[] args) {
A a = TestGenerics.<A>getCAsT();
B b = TestGenerics.<B>getCAsT();
a.a();
b.a();
}
}
Otherwise, I would try to merge the two interfaces in some way.

calling derived class method using base class object

I have 6 classes as shown in figure below.
Now, class A has an object of class B as a private variable defined. Also class A methods calls many methods from class B, for example B.method1().
Now, class A_Base1 is which is derived from class A, needs to call methods from the derived class B_Base1; for example B1.method2(). And also methods of class A_Base2 needs to call methods from class B_Base2; for example B2.method3().
Now in class A I define the variable as -
private B bObject
Now in method of A_Base1, I cannot cannot call the methods like bObject.method2() since its a base class object.
I need suggestions on -
Is it possible to call derived class object methods using base class object?
Or do I need to re-design this scenario in some other good way?
Using inheritance like this imo only makes sense if the Bx.methodX() do something that means she same to the different Ax. And in that case, you should name them that way:
public class B {
public void doWhatAMeans() {
method1();
}
public class B1 extends B {
#Override
public void doWhatAMeans() {
method2();
}
public class B2 extends B {
#Override
public void doWhatAMeans() {
method3();
}
and then you only need A to call doWhatAMeans() and the A1 and A2 only need to be injected the appopriate instances of Bx.
On the other hand, if doWhatAMeans does not make sense because the methodX do different things that mean different things to Ax, then you need to rethink your object model, probably the parallel structures A,A1,A2 and B,B1,B2 are wrong then.
you could always cast. suppose your class A provides this method:
protected B getBInstance() {
return bObject;
}
then in A_Base1 you could do something like:
((B_Base1)getBInstance()).method2();
this, however, is a VERY bad design. if your A_Base1 class needs an instance of B_Base1 it should be handed such an instance directly at construction time:
public class A_Base1 extends A {
private B_Base1 b1Object;
public A_Base1(B_Base1 instance) {
super(B_Base1); //works as a B for parent
this.b1Ovject = instance;
}
}
and then you can use that
since A is a parent of A_Base1 (I'm assuming extended) you can make the function call that Accesses B public (or protected) and then A_Base1 or A_Base2 can use the same function A does to call into B.

super.super.func()? - Java polymorphism

Say that I in Java have 3 classes, wheres the super one has a function named func(), I now make a subclass which overrides this, and a subclass to my subclass, now working on my sub-sub-class how will I call the 'func()' of the sub class, and the superclass?
I tried casting the 'this' "pointer", but Java 'fixes' it at runtime and calls the subsub func().
Edit:
Thanks everyone; 'Skeen is back at the drawing board'.
The best you can do is call super.func() in your subsub class, and have the func() implementation in your subclass also call super.func().
However, ask yourself, if I need knowledge not only of my parents implementation but also my grandparents implementation, do I have a design problem? Quite frankly this is tripping my "Something stinks in the fridge" instinct. You need to re-evaluate why you want to do this.
This isn't possible in Java. And btw. there aren't any pointers in Java.
I would jump on the "something in this design smells funny" train. Normally, you override a method so that it works properly for that specific subclass. If you have code in your parent class that is shared across multiple subclasses, perhaps that code could be moved to a non-overridden method so that it is readily accessible by all children/granchildren/etc.
Could you perhaps flip your design over and use more of a template method approach? (http://en.wikipedia.org/wiki/Template_method_pattern)
The notion behind Template Method is that you have some algorithm in your parent class and you can fill in the pieces that need to be class specific by polymorphic calls into your subclasses. You don't have a ton of detail in your question, but by the sounds of things, I'd really take a good look at your design and see if it makes sense.
Why don't you have func() be not inherited (call it funcBase() or whatever) and then add a wrapper func() function that calls it?
class A{
public void funcBase() {
// Base implementation
}
public void func() {
funcBase();
}
}
class B extends A{
public void func(){
super.func();
}
}
class C extends B{
public void foo(){
super.func(); // Call B's func
funcBase(); // Call A's func
}
}
I have no idea what you're trying to do, but it sounds like your class design is not appropriate for what you want, so you may want separate functions in A instead of trying to sneak your way up the ladder.
This example is the only way to call a "grandparent" super method.
class A{
public void foo(){ System.out.println("Hi"); }
}
class B extends A{
public void foo(){ super(); }
}
class C extends B{
public void foo(){ super(); }
}
This would be a different story if B doesn't override foo().
Another option would be to have a "protected helper" method in the middle class.
class D{
public void foo(){ System.out.println("Hi"); }
}
class E extends D{
public void foo(){ System.out.println("Hello"); }
protected void bar(){ super.foo(); }
}
class F extends E{
public void foo(){ super.bar(); }
}
You can access the superclass methods from within the subclass itself, e.g.
class A {
void foo() {...}
}
class B extends A {
void foo() {...}
void defaultFoo() { super.foo(); }
}
However, you really shouldn't be exposing overridden methods this way, you should write B.foo() in such a way that works fine for A and B. This is where it is a good idea to use super.foo(); like this:
class B extends A {
void foo() {
super.foo(); //call superclass implementation first
... //do stuff specific to B
}
}
Update: In response to your comment on trying to access the implementation 2 levels up, here's a way of doing it.
class A {
void foo() {
defaultFoo();
}
protected void defaultFoo() { ... }
}
class B extends A {
void foo() {...}
}
class C extends B {
void foo() {
defaultFoo();
... //do other stuff
}
}
This is a healthier pattern of coding what you want to do.
You should probably rethink how you are handling your class hierarchy if you need to place a call to a function that is defined two levels up the hierarchy. Consider writing new methods that are implemented by each subclass in a different way.

how to pass a self-reference to constructors in java?

i have a class A that needs to instantiate a second class B, whose constructor needs a reference to the same object of class A...
would look like:
public class A {
B b;
public A() {
b = new B(this);
}
}
public class B {
A a;
public B(A a) {
this.a = a;
}
}
well - eclipse keeps complaining that this isnt possible. i assume, this is because the reference of class A isnt "ready" yet at this moment...?
but the error wont go away if i move the init of class B to a seperate function within A wich i would call from "outside"...
how can i pass this self-reference from outside to the constructor of B?
Be very careful, because until A is constructed, it doesn't really exist. If B were to call a method on A, the program should fail because you can't call a method on A prior to A being constructed. Construction is not complete until A fully returns from its constructor code.
If you must initialize B with A whenever A is constructed, it is much better to make a factory class for A which guarantees that B is initialized after A is constructed. It would look something like this
public class AFactory {
public A newA() {
A a = new A();
B b = new B(a);
return a;
}
}
For this to work properly 100%, you might need to limit the visibility of the A() constructor. I personally would put AFactory into the same package as A and make the access "default" or "package private like so
package same.as.afactory;
public class A {
A() {
...
}
}
I'd ask myself: Are you sure that's the design you want? And, if it is, would it make sense for one of those classes to be an inner class of the other?
Look, here is a way to use a constructed self instance in the constructer itself:
public class Foo {
private int x;
public Foo() {
this(1);
// the self instance should have been constructed now
}
public Foo(int x) {
this.x = x;
}
}
How do I call one constructor from another in Java?
Create a holder object which you can pass from A to B, and then insert the this instance of A into when the A constructor is finished. Then B can refer to the this-value inside the holder later.

Categories