Java - Confused about a particular inheritance scenario - java

Say I have a class called A, and in A there's a method called myMethod(). Now say I make a subclass of A, called SubA, and in SubA I override myMethod() to make it do what I want it to. Now say I have another method in A called myOtherMethod() which calls myMethod() (from within the same class). I do not override myOtherMethod() in SubA. If I now call myOtherMethod() from inside SubA, it will clearly run A's myOtherMethod(). But does this now call the myMethod() as defined in A, or as defined (and overridden) in SubA?
To further confuse things, does it matter at all whether myMethod() were an interface method for some interface that class A implemented?

It is easy to try - the fact that A implements an interface or not does not make a difference:
public class A {
public void myMethod() {
System.out.println("A.myMethod()");
}
public void myOtherMethod() {
System.out.println("A.myOtherMethod()");
myMethod();
}
public static class SubA extends A {
#Override
public void myMethod() {
System.out.println("SubA.myMethod()");
}
}
public static void main(String[] args) {
A a = new A();
SubA subA = new SubA();
a.myMethod(); //A.myMethod()
subA.myMethod(); //SubA.myMethod()
a.myOtherMethod(); //A.myOtherMethod() + A.myMethod()
subA.myOtherMethod(); //A.myOtherMethod() + SubA.myMethod()
}
}

If you create instance of SubA then calling method myOtherMethod() (which is in A) calls method myMethod() defined in SubA because it overrides method defined in A.

Related

If a child class extend Base class Exception

I had a doubt.
Imagine If we have a class A that implements the method
For example
private void methodA(int index) throws Exception, Error {
}
And if we have a Class B that extends the first class A.
My questions is, can class B implement
private void methodA(int index) throws Exception, Error {
}
And which method will be called under which circumstance!!
Thanks
If your methods weren't declared "private", this would just be standard polymorphism. Because they're private, the rules are a bit different. The version in class A can only be called from code that's in class A. The version in class B can only be called from code that's actually written in class B (as opposed to code that class B gets by extending class A).
YES, you can implement the methodA method in class B, but, pay attention, you are not overriding it.
Your method is declared ad private so is not "visible" from extending classes.
If your intention is to make your method overridable, you need to declare it as public.
Just give it a try :)
public class Main {
public static void main(String[] args) {
Base base;
base = new A();
System.out.println(base.doSth());
base = new B();
System.out.println(base.doSth());
}
}
abstract class Base {
public abstract String doSth();
}
class A extends Base {
#Override
public String doSth() {
return "A";
}
}
class B extends A {
#Override
public String doSth() {
return "B";
}
}
I think you wonna override the super-class method, and to do this, the method on sub-class must have the same signature of super-class method.
You can call these methods in following ways:
Suppose test1 is an instance of classA, teste1.methodA(index) will execute the implementation on super-class.
Suppose test2 is an instance of classB, test2.methodA(index) will execute the sub-class method.
In classB you can invoque the super class method (if the method is notprivate), something like :
public class ClassB extends ClassA
{
...
super.methodA(index);
...
}

Overriding a base class method in a derived class

I have a base class A, having a method "say" that calls from constructor of A. All the heritable classes uses the method "say" like it is. But one of the classes need to redefine this method. How is it possible?
For sure, I can denote base method "say" as abstract, but in that way, i have to copy the same method "say" in all the heritable classes.
If i just redefine method without denoting base one as abstract, it is not gonna be called.
public abstract class A(){
public A(){
say(); // <- wanna call this method from heritable class, if its redefined.
}
protected void say(){};
}
public class B extends A(){
public B(){
super();
}
private void say(){};
}
refactoring 1
public abstract class A(){
public A(){
// constructor methods
}
protected void say(){};
protected void executeSay(){
say();
}
}
public class B extends A(){
public B(){
super();
executeSay();
}
#Override
protected void say(){};
}
First of all one must be made clear: calling an overridable method from a constructor is a well-known antipattern. It will almost certainly break your code because the subclass method will be invoked before the subclass constructor is done and so will observe an uninitialized object. Thus I should better refrain from giving you detailed advice on Java technicalities involved in achieving this antipattern.
The only safe way to acomplish your requirement is to let the construction finish and only afterwards call an initialize-kind of method. If you want to ensure initialize is always invoked, make the constructors non-public and provide a factory method instead.
Unfortunately, Java requires quite a bit of work on your part to make this work properly.
You cannot instantiate a abstract class. That saying you have to link the abstract class reference to the concrete inherited class.
eg. A a = new B();
If that's the case, and B have redefined the say() method, then the say method in B will be called.
public class TestPad {
public static void main(String[] args) {
A a = new B();
}
}
abstract class A {
public A() {
say();
}
public void say(){
System.out.println("A");
};
}
class B extends A {
public B() {
super();
}
public void say() {
System.out.println("B");
}
}
The output will be B
public class B extends A {
public B() {
super();
}
#Override
protected void say() {
// your diffent say code
};
}
I'm not sure if you are allowed to reduce visibility to private.
Because of polymorphic method invocation, in your case the B.say() will be invoked if you override it.
But as #sanbhat commented, you need to change visibility of say() to protected.

Can a private method in super class be overridden in the sub-class?

Can private methods be overridden in Java?
If no, then how does the following code work?
class Base{
private void func(){
System.out.println("In Base Class func method !!");
};
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("In Derived Class func method");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func();
}
}
No, you are not overriding it. You can check by trying to mark it with #Override, or by trying to make a call to super.func();. Both won't work; they throw compiler errors.
Furthermore, check this out:
class Base {
private void func(){
System.out.println("In base func method");
};
public void func2() {
System.out.println("func2");
func();
}
}
class Derived extends Base {
public void func(){ // Is this an overriding method?
System.out.println("In Derived Class func method");
}
}
class InheritDemo {
public static void main(String [] args) {
Derived D = new Derived();
D.func2();
}
}
It will print:
func2
In base func method
When you change func() in Base to public, then it will be an override, and the output will change to:
func2
In Derived Class func method
No, a private method cannot be overridden because the subclass doesn't inherit its parent's private members. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class. There is no way an overriding method would be banned from accessing the method it is overriding, but this would precisely be the case here.
No, it is not. You can mark an override just to make sure like this:
#Override
public void func(){
System.out.println("In Derived Class func method");
}
And in this case it would be a compiler error.
You are not overriding. You cannot override private members, you are merely defining a new method in Derived. Derived has no knowledge Base's implementation of func() since its declared as private. You won't get a compiler error when you define func() in Derived but that is because Derived does not know Base has an implementation of func(). To be clear: it would be incorrect to say you are overriding Base's implementation of func().
In addition to the already correct answer, consider this:
public class Private {
static class A {
public void doStuff() {
System.out.println(getStuff());
}
private String getStuff() {
return "A";
}
}
static class B extends A {
public String getStuff() {
return "B";
}
}
public static void main(String[] args) {
A a = new A();
a.doStuff();
a = new B();
a.doStuff();
B b = new B();
b.doStuff();
}
}
This will print
A
A
A
although B "overrides" getStuff(). As implementation of doStuff() is fixed to calling A#getStuff(), no polymorphism will be triggered.
Nope because if you do something like Base b = new Derived(); you still won't be able to call b.func(). What you're doing is called "hiding".
Since the method is private it is not visible to the other classes.Hence the derived class does not inherit this method.
So this is not the case of overriding
Method hiding will be happening here instead of overriding. like what happens in case of static.
Actually,you are not overriding.Before Java5
an overridden method's return type must match with parent class's method.
But Java 5 introduced a new facility called covariant return type.You can override a method with the same signature but returns a subclass of the object returned. In another words, a method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.
you can follow this thread :Can overridden methods differ in return type?
The private member of the base class cannot be access by anyone outside of the class and cannot be overridden. The function in the derive class is an independent function that can be access by anywhere.
The code would run the function in the derived class
A private method can never be over ridden. It is always hidden.
In your example - Derived class has one parent class private method and has its own function func. Both are different, and the func is not over ridden. Its a separate independent function.
If you create a new function in parent class calling parent class function, the parent func will be called, if parent class reference is used as opposed in the case of method over ridding
Note : An object defines the members which it has, and a reference defines which it can access
// Method Over ridding case
class Base{
public void func(){
System.out.println("Parent class");
};
public void func1(){
func();
}
}
class Derived extends Base{
public void func(){
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1(); // Prints Derived class - no matter parent reference is calling,as there as method is overridden - Check func1() is in parent class, but id doesn't call parent class func() as the compiler finds a func() method over ridden in derived class
}
}
// Method Hidding case - Private and static methods case
class Base{
private void func(){
System.out.println("Parent class");
};
public void func1(){
func()
}
}
class Derived extends Base{
public void func(){ // Is this a Method Overriding..????
System.out.println("Derived class");
}
}
class InheritDemo{
public static void main(String [] args){
Derived d = new Derived();
d.func1(); // Prints Derived class
Base b = new Derived();
b.func1();
// Prints Parent class - the reason is we are using the parent class reference, so compiler is looking for func() and it founds that there is one private class method which is available and is not over ridden, so it will call it. Caution - this won't happen if called using derived class reference.
b.func();
// this prints the Derived class - the compiler is looking func(), as Derived class has only one func() that it is implementing, so it will call that function.
}
}
Read comments in the below code snippet to find the answer.
Sources:
Definition reference:
Credits for the source code example(reference) from the book - "OCA Oracle Certified Associate Java SE 8 Programmer Study Guide Exam 1Z0-808 Book" from 'Jeanne Boyarsky' and 'Scott Selikoff'.
public class Deer {
public Deer() { System.out.print("Deer"); }
public Deer(int age) { System.out.print("DeerAge"); }
private boolean hasHorns() { return false; }
public static void main(String[] args) {
Deer deer = new Reindeer(5);
System.out.println(","+deer.hasHorns());// false is printed.
}
}
class Reindeer extends Deer {
public Reindeer(int age) { System.out.print("Reindeer"); }
private boolean hasHorns() { return true; } // Overriding possible, but is of no use in the below context.
// Below code is added by me for illustration purpose
public static void main(String[] args) {
Deer deer = new Reindeer(5);
//Below line gives compilation error.
//System.out.println(","+deer.hasHorns());
}
}

Calling super super class method

Let's say I have three classes A, B and C.
B extends A
C extends B
All have a public void foo() method defined.
Now from C's foo() method I want to invoke A's foo() method (NOT its parent B's method but the super super class A's method).
I tried super.super.foo();, but it's invalid syntax.
How can I achieve this?
You can't even use reflection. Something like
Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
superSuperClass.getMethod("foo").invoke(this);
would lead to an InvocationTargetException, because even if you call the foo-Method on the superSuperClass, it will still use C.foo() when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.
It seems you need help from the B class (e.g. by defining a superFoo(){ super.foo(); } method).
That said, it looks like a design problem if you try something like this, so it would be helpful to give us some background: Why you need to do this?
You can't - because it would break encapsulation.
You're able to call your superclass's method because it's assumed that you know what breaks encapsulation in your own class, and avoid that... but you don't know what rules your superclass is enforcing - so you can't just bypass an implementation there.
You can't do it in a simple manner.
This is what I think you can do:
Have a bool in your class B. Now you must call B's foo from C like [super foo] but before doing this set the bool to true. Now in B's foo check if the bool is true then do not execute any steps in that and just call A's foo.
Hope this helps.
To quote a previous answer "You can't - because it would break encapsulation." to which I would like to add that:
However there is a corner case where you can,namely if the method is static (public or protected). You can not overwrite the static method.
Having a public static method is trivial to prove that you can indeed do this.
For protected however, you need from inside one of your methods to perform a cast to any superclass in the inheritance path and that superclass method would be called.
This is the corner case I am exploring in my answer:
public class A {
static protected callMe(){
System.out.println("A");
}
}
public class B extends A {
static protected callMe(){
System.out.println("B");
}
}
public class C extends B {
static protected callMe(){
System.out.println("C");
C.callMe();
}
public void accessMyParents(){
A a = (A) this;
a.callMe(); //calling beyond super class
}
}
The answer remains still No, but just wanted to show a case where you can, although it probably wouldn't make any sense and is just an exercise.
Yes you can do it. This is a hack. Try not to design your program like this.
class A
{
public void method()
{ /* Code specific to A */ }
}
class B extends A
{
#Override
public void method()
{
//compares if the calling object is of type C, if yes push the call to the A's method.
if(this.getClass().getName().compareTo("C")==0)
{
super.method();
}
else{ /*Code specific to B*/ }
}
}
class C extends B
{
#Override
public void method()
{
/* I want to use the code specific to A without using B */
super.method();
}
}
There is a workaround that solved my similar problem:
Using the class A, B, and C scenario, there is a method that will not break encapsulation nor does it require to declare class C inside of class B. The workaround is to move class B's methods into a separate but protected method.
Then, if those class B's methods are not required simply override that method but don't use 'super' within that method. Overriding and doing nothing effectively neutralises that class B method.
public class A {
protected void callMe() {
System.out.println("callMe for A");
}
}
public class B extends A {
protected void callMe() {
super.callMe();
methodsForB(); // Class B methods moved out and into it's own method
}
protected void methodsForB() {
System.out.println("methods for B");
}
}
public class C extends B {
public static void main(String[] args) {
new C().callMe();
}
protected void callMe() {
super.callMe();
System.out.println("callMe for C");
}
protected void methodsForB() {
// Do nothing thereby neutralising class B methods
}
}
The result will be:
callMe for A
callMe for C
It's not possible, we're limited to call the superclass implementations only.
I smell something fishy here.
Are you sure you are not just pushing the envelope too far "just because you should be able to do it"? Are you sure this is the best design pattern you can get? Have you tried refactoring it?
I had a problem where a superclass would call an top class method that was overridden.
This was my workaround...
//THIS WOULD FAIL CALLING SUPERCLASS METHODS AS a1() would invoke top class METHOD
class foo1{
public void a1(){
a2();
}
public void a2(){}
}
class foo2 extends foo1{
{
public void a1(){
//some other stuff
super.a1();
}
public void a2(){
//some other stuff
super.a2();
}
//THIS ENSURES THE RIGHT SUPERCLASS METHODS ARE CALLED
//the public methods only call private methods so all public methods can be overridden without effecting the superclass's functionality.
class foo1{
public void a1(){
a3();}
public void a2(){
a3();}
private void a3(){
//super class routine
}
class foo2 extends foo1{
{
public void a1(){
//some other stuff
super.a1();
}
public void a2(){
//some other stuff
super.a2();
}
I hope this helps.
:)
Before using reflection API think about the cost of it.
It is simply easy to do. For instance:
C subclass of B and B subclass of A. Both of three have method methodName() for example.
public abstract class A {
public void methodName() {
System.out.println("Class A");
}
}
public class B extends A {
public void methodName() {
super.methodName();
System.out.println("Class B");
}
// Will call the super methodName
public void hackSuper() {
super.methodName();
}
}
public class C extends B {
public static void main(String[] args) {
A a = new C();
a.methodName();
}
#Override
public void methodName() {
/*super.methodName();*/
hackSuper();
System.out.println("Class C");
}
}
Run class C Output will be:
Class A
Class C
Instead of output:
Class A
Class B
Class C
In my simple case I had to inherit B and C from abstract class, that incapsulates equal methods of B and C. So that
A
|
Abstr
/ \
B C
While it doesn't solve the problem, it can be used in simple cases, when C is similar to B. For instance, when C is initialized, but doesn't want to use initializers of B. Then it simply calls Abstr methods.
This is a common part of B and C:
public abstract class Abstr extends AppCompatActivity {
public void showProgress() {
}
public void hideProgress() {
}
}
This is B, that has it's own method onCreate(), which exists in AppCompatActivity:
public class B extends Abstr {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Call from AppCompatActivity.
setContentView(R.layout.activity_B); // B shows "activity_B" resource.
showProgress();
}
}
C shows its own layout:
public class C extends Abstr {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Call from AppCompatActivity.
setContentView(R.layout.activity_C); // C shows "activity_C" resource.
showProgress();
}
}
This is not something that you should do normally but, in special cases where you have to workaround some bug from a third party library (if it allow to do so), you can achieve calling a super super class method that has already been overwritten using the delegation pattern and an inner class that extends the super super class to use as a bridge:
class A() {
public void foo() {
System.out.println("calling A");
}
}
class B extends A() {
#Overwrite
public void foo() {
System.out.println("calling B");
}
}
class C extends B() {
private final a;
public C() {
this.a = new AExtension();
}
#Overwrite
public void foo() {
a.foo();
}
private class AExtension extends A {
}
}
This way you will be able to not only call the super super method but also combine calls to other super super class methods with calls to methods of the super class or the class itself by using `C.super` or `C.this`.

Is it possible to override a static method in derived class?

I have a static method defined in a base class, I want to override this method in its child class, is it possible?
I tried this but it did not work as I expected. When I created an instance of class B and invoke its callMe() method, the static foo() method in class A is invoked.
public abstract class A {
public static void foo() {
System.out.println("I am base class");
}
public void callMe() {
foo();
}
}
Public class B {
public static void foo() {
System.out.println("I am child class");
}
}
Static method calls are resolved on compile time (no dynamic dispatch).
class main {
public static void main(String args[]) {
A a = new B();
B b = new B();
a.foo();
b.foo();
a.callMe();
b.callMe();
}
}
abstract class A {
public static void foo() {
System.out.println("I am superclass");
}
public void callMe() {
foo(); //no late binding here; always calls A.foo()
}
}
class B extends A {
public static void foo() {
System.out.println("I am subclass");
}
}
gives
I am superclass
I am subclass
I am superclass
I am superclass
In Java, static method lookups are determined at compile time and cannot adapt to subclasses which are loaded after compilation.
Just to add a why to this. Normally when you call a method the object the method belongs to is used to find the appropriate implementation. You get the ability to override a method by having an object provide it's own method instead of using the one provided by the parent.
In the case of static methods there is no object to use to tell you which implementation to use. That means that the compiler can only use the declared type to pick the implementation of the method to call.
No. It's not possible.
Some similar (not the same) questions here and here.
Static Methods are resolved at compile time.So if you would like to call parent class method then you should explicitly call with className or instance as below.
A.foo();
or
A a = new A();
a.foo();
In a nutshell static method overriding is not polymorphism it is "method hiding".
When you override a static method you will have no access to the base class method as it will be hidden by the derived class..
Usage of super() will throw a compile time error..

Categories

Resources