This question already has answers here:
How to call the overridden method of a superclass?
(12 answers)
Closed 9 years ago.
This question was asked to me in an interview. I have an overridden method in my sub-class. Using an instance of the subclass, I want to call the method of the super class. Bear in mind that the method is overridden.
The output of the following code is NO NO PRINT HI.
What if I want to print Print Hello using the object of overriding class? How do I do that?
class OverrideSuper {
public void printHello() {
System.out.println("Print Hello");
}
}
public class Overriding extends OverrideSuper {
public void printHello() {
System.out.println("NO NO PRINT HI");
}
public static void main(String[] args) {
//OverrideSuper obj1 = new OverrideSuper();
Overriding obj2 = new Overriding();
obj2.printHello();// this calls printHello() of class Overriding.
//I want to call printHello() of OverrideSuper using obj2. How do I do that???
}
}
I think the interviewer expected you to write another method that calls super.printHello():
public class Overriding extends OverrideSuper {
public void printHello(){
System.out.println("NO NO PRINT HI");
}
public void superHello() { // You can make this private or protected, too
super.printHello();
}
public static void main(String[] args) {
//OverrideSuper obj1 = new OverrideSuper();
Overriding obj2 = new Overriding();
obj2.superHello();// this calls printHello() of class OverrideSuper .
}
}
Essentially, he wanted you to tell him that once a method is overriden, there is no way to call through to the method of the base class from the outside. The only way around it is to make a calling path into the superclass on the inside of the overriding class, which is what I did above by defining a superHello method.
[The interviewer] said "I am not convinced"
Another possibility could be that the interviewer was looking for you to provide a reflection-based solution, which is possible only in Java 7+. You need to use MethodHandle, call findSpecial with the base class, and then invoke the method that you get back.
Here is a link to an answer that explains the process, and shows an example.
i think this will fulfil your requirement!! try this
when you call obj2.printHello(); execution will move to Overridings printHello() and in that method i ve used super.printHello(); this means first invoke super class's printHello() and compiler prints Print Hello then execution again come to Overridings printHello() and print NO NO PRINT HI
class OverrideSuper {
public void printHello() {
System.out.println("Print Hello");
}
}
public class Overriding extends OverrideSuper {
public void printHello() {
super.printHello();
System.out.println("NO NO PRINT HI");
}
public static void main(String[] args) {
// OverrideSuper obj1 = new OverrideSuper();
Overriding obj2 = new Overriding();
obj2.printHello();// this calls printHello() of class Overriding.
// I want to call printHello() of OverrideSuper using obj2. How do I do
// that???
}
}
output
Print Hello
NO NO PRINT HI
You can use the super keyword to access the parent method.
class OverrideSuper{
public void printHello(){
System.out.println("Print Hello");
}
}
public class Overriding extends OverrideSuper {
public void printHello(){
super.printHello();
//System.out.println("NO NO PRINT HI");
}
public static void main(String[] args) {
//OverrideSuper obj1 = new OverrideSuper();
Overriding obj2 = new Overriding();
obj2.printHello();// this calls printHello() of class Overriding.
//I want to call printHello() of OverrideSuper using obj2. How do I do that???
}
}
Related
How to call parent overridden method. Because when I call same method, overridden method of child class is called. But what if i want to call parent method explicitly through object, how can i do it? I want "hello B" as output.
class B
{
B()
{
System.out.println("B");
}
void display()
{
System.out.println("hello B");
}
}
class A extends B
{
A()
{
System.out.println("A");
}
void display()
{
System.out.println("hello A");
}
public static void main(String[] args)
{
A a= new A();
a.display();
}
}
output:
B
A
hello A
expected:
B
A
hello B
The instance you created is an A instance. Wherever A has an implementation for a method like display(), that one (A.display() ) will be called and get control. Always.
A.display() can decide that it'll use the parent's implementation by calling super.display() somewhere in its body. You can't do it from outside, only the A.display() method itself can do so.
When you design a class, you decide how its instances will react to method calls. If you override a method, you have a reason to do so: with a child instance, the parent implementation won't do what the method name demands. So, were it possible to call the parent method from outside, things would generally go wrong.
Try like this:
public class A extends B {
public A() {
System.out.println("A");
}
void display() {
System.out.println("hello A");
}
void displayB() {
super.display();
}
public static void main(String[] args) {
//first it will go to A constructor
//from A, constructor first it will execute the super();
//due to inheritance concept, execute B block statements //print "B"
//then it will execute the A block statements //print "A"
//after that it will execute the method, which will print the parent class method
new A().displayB();
}
}
I have two java class files
Hi.java which belongs to second package
package second;
public class Hi {
protected int v=20;
protected void m(){
System.out.println("i am protectTED");
}
}
S.java which belong to first package
package first;
import second.Hi;
interface i1
{
void m();
int a=200;
}
interface i2{
void m1();
int b=100;
}
class S extends Hi implements i1,i2
{
int a=50;
public void m()
{
System.out.println("hi");
}
public void m1()
{
System.out.println("hello");
}
public static void main(String[] args) {
S s=new S();
/*need correction here (i don't know the exact syntax to mention to get
the desired output)
s.m(); //should invoke method m() from class Hi only.
s.m(); //Should invoke method m() from class S only.
*/
//the following statements prints the desired values
s.m1();
System.out.println(s.v);
System.out.println(i1.a);
System.out.println(s.a);
System.out.println(b);
}
}
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
How to differentiate the 2 methods for invoking. Is it even possible?
when i run the S.java class file method m() in class Hi should be invoked.("my intention") instead method m() of the same class i.e., class S is being invoked.
Correct, because you've overridden it with m in S. Overriding methods is fundamentally different from overriding fields. (And in general, it's best to avoid overriding any fields that are visible to your subclass, as you're doing with a.)
In instance code in S, you can run the inherited m via super: super.m(). But you cannot do that from static code, not even static code in S. You could give yourself a private callSuperM in S:
private void callSuperM() {
super.m();
}
...and then use that in main:
s.callSuperM(); // "i am protectTED"
s.m(); // "hi"
This question already has answers here:
Calling super super class method
(12 answers)
Closed 7 years ago.
I have faced a question in an interview whether we can access the method display() of class ABC from EDC as given below
class ABC {
public void display() {
System.out.println("from ABC");
}
}
class CBD extends ABC {
public void display() {
System.out.println("From CBD");
}
}
class EDC extends CBD {
public void display() {
System.out.println("From EDC");
}
}
I would like to know if we can access the method of ABC from class EDC other than an object creation of ABC. I know the answer is very straight and simple that we can access only the super class method of EDC i.e; display() of CBD through super.display(), but I am feeling whether I am missing any approach here to access the display() of ABC from EDC.
I think one of the possible approaches is as below
class ABC {
public void display()
{
System.out.println("from ABC");
}
public static void main(String args[])
{
ABC obj=new EDC();
obj.display();
}
}
class CBD extends ABC {
public void display()
{
super.display();
}
}
class EDC extends CBD {
public void display()
{
super.display();
}
}
No, it is not possible. You can only go one level up with super.
You could have a method that calls super() from CBD and call that method from EDC using super(), i.e. chain the calls.
In java, how can you get the object calling a method, within the method it is calling, if the method is in another class? I have looked all over the internet and no solution. Could someone please help?
The only way I can think of is to pass this to the method,
static void someMethod(Object o) {
System.out.println(o);
}
void testIt() {
someMethod(this); // <-- pass the current instance to the method.
}
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace()
The last element of this array will be the recent object you have used. But it should better to use an extra argument as above answer said and pass this object.
If you know in advance that you need to receive an instance of the first class then you can prepare the second class to receive it as follows.
public class class1 {
public static void main(String[] args)
{
new class1();
}
public class1()
{
send();
}
private void send()
{
new class2().receiveClass(this);// creates an instance of class 2 and sends a reference of class1 (this)
}
public void print()
{
System.out.println("class1.print()");
}
}
To receive in the second class.
public class class2 {
private class1 c1;
public void receiveClass(class1 c)
{
c1=c;
c1.print(); //accessing the print method of class1, the same instance that references this object.
}
}
This will also work if the solutions given above do not work for you.
This question already has answers here:
Interface and Abstract class ad method overriding
(3 answers)
Closed 8 years ago.
Class A has run() method and interface B also has run() method. Question is simple, which run() method is overridden in Main class and how will we prove this? Why there is no conflict (Compile-time error) in this code?
class A{
void run(){System.out.println("A class");}
}
interface B{
void run();
}
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
// Overridding method
public void run(){
System.out.println("run method");
}
}
run of A is overridden, run of B is implemented. As B is an interface, it only states how your objects behave to others and don't enforce any behavior itself.
run() Method of Interface B will be Implemented in class Main by
overridden method of Class A.
Adding an extra point,
It you will not write the run() method in child class Main, You will not get well known "Unimplemented methods" error. This is true for public methods of class A for non public methods you will get compiler error : The inherited method can not hide public abstract method.
That is because methods of interface are public by default and you can not hide it with default (package private) access modifier.
Sample :
class A{
public void run() {
System.out.println("This method will be inherited.");
}
}
interface B{
void run();
}
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
}
OUTPUT : This method will be inherited.
In above code instance, the run() method is inherited from class A that will implement run() method of interface B.
What will be called is
public void run(){
System.out.println("run method");
}
Why?
You're implementing run of interface B and you're also overriding the A implementation of it.
If you remove the last run() implementation and remove implements B, run() of A will be called.
Interface B says that any class implementing it must have a run method. Main extends A and inherits A's run() method.
Main meets the requirement of the B interface for having a run method. The run method in Main then overrides the run() method it got from the A class.
// This is a class with a run method.
class A{
void run(){System.out.println("A class");}
}
// Anything implementing this interface must have a run method.
interface B{
void run();
}
// This class is an extension of A (and therefore has A's run() method)
// This class implements B and must have a run method, which it does, because it has A's
class Main extends A implements B{
public static void main(String args[]){
Main m = new Main();
m.run();
}
// This method then overrides the run Method it inherited from A
// And this method meets the requirement set by implementing B.
public void run(){
System.out.println("run method");
}
}
There is no conflict because both methods have the same signature. Method declarations in interfaces are not overridden because they don't implement anything. So in this case, run method in class A is overridden.
On the other hand, when overriding methods you are encouraged to use the #Override annotation, e.g.
#Override
public void run() {
....
}
Super class's method is always called as overridden method whereas subclass method is called as overriding method.
Final method cannot be overridden. [if superclass's method is final]
Final methods can override. [Read it as grammatical way. This method is in subclass and is final, but superclass's method is not final]