Method Overriding using super keyword - java

I have one doubt, Please see the following code. i have three classes A,B and InheritanceExample. Here I am calling the super.run() from the main class; it is calling the B class run() method.
Is there any option to call A class run method from the main class (InheritanceExample) with out creating an instance for class A?
class A
{
void run()
{
System.out.println("<<<====Class A run Method===>>>>");
}
}
class B extends A
{
void run()
{
System.out.println("<<<====Class B run Method===>>>>");
super.run();
}
}
public class InheritanceExample extends B{
/**
* #param args
*/
void run()
{
System.out.println("<<<====Main Class run Method===>>>>");
super.run();
}
public static void main(String[] args) {
InheritanceExample a = new InheritanceExample();
a.run();
}
}

Since B extends A and InheritanceExample extends B you are creating an instance. Make method A.run() static.
class A
{
void static run()
{
System.out.println("<<<====Class A run Method===>>>>");
}
}
class B
{
void run()
{
System.out.println("<<<====Class B run Method===>>>>");
A.run();
}
}
public class InheritanceExample extends B {
#Override
void run()
{
System.out.println("<<<====Main Class run Method===>>>>");
super.run();
}
public static void main(String[] args) {
InheritanceExample a = new InheritanceExample();
a.run();
}
}

No.
Not without making A.run() different from B.run(), such as by making A.run() static.
When B extends A, you as a programmer must ensure that from the callers perspective B "is-a" A. What you want to do is to break this rule.
If you want to use a B as an A, you are probably trying to do something at the calling point, that should be handled internally in B.

Not sure what you want to achieve. But looking at the class hierarchy and structure, it is not possible to directly call run method of Class A. But if we change and introduce a additional static method say runImpl in Class A, and call same method from run method of Class A. Now we can call runImpl from anywhere as it is static and run method too internally is calling runImpl so same implementation is getting call via run and runImpl.
Below is the code snippet:
class A
{
void run()
{
runImpl();
}
public static void runImpl(){
System.out.println("<<<====Class A run Method===>>>>");
}
}
class B extends A
{
void run()
{
System.out.println("<<<====Class B run Method===>>>>");
super.run();
}
}
public class InheritanceExample extends B{
/**
* #param args
*/
void run()
{
System.out.println("<<<====Main Class run Method===>>>>");
super.run();
}
public static void main(String[] args) {
A.runImpl();
}
}

class a{
void run(){
System.out.println("runing method run of a clss");
}
}
class b extends a{
void run(){
super.run();
System.out.println("runing method run of b clss");
}
}
class InheritanceExample extends b{
void run(){
super.run();
System.out.println("running method run in inheritance class");
}
}
class pratics{
public static void main(String[] args){
System.out.println("********");
InheritanceExample a1=new InheritanceExample();
a1.run();
System.out.println("********");
}
}

Related

Where can we use the scenario where we can create an anonymous class when we do it for an Interface?

Interface :
public interface MyFirstInterface {
void myFirstAbstractMethod();
default void myDefaultMethod() {
System.out.println("Hi I am default method in Interface.");
}
}
Class:
public class MyFirstClass{
public static void main(String[] args) {
MyFirstInterface myFirstInterface = new MyFirstInterface() {
#Override
public void myMethod() {
System.out.println("Main class : "+this.getClass());
}
};
myFirstInterface.myMethod();
myFirstInterface.defaultMethod();
}
}
Now we know we are instantiating a anonymous class, what I want to know is Why would anyone use it? What is the advantage or disadvantage of doing it?
It is not a constructor. It is a method a() declaration with the return type A.
Also, we can instantiate an interface using an anonymous class. Runnable for example:
Runnable r = new Runnable() {
#Override
public void run() { ... }
};
Runnable r = () -> { ... }

In Java is it possible to check at runtime on which subclass a method was called?

interface Y {
void search(String name);
}
class A implements Y {
void search(String name) {
//Is it possible to say: "If I was called from class B then do a search("B");
}
}
class B extends A {
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search();
}
}
Given the above code is it possible to reason in superclass which subclass was used for calling a method?
The reason I want to do this is because the code in Search is very similar for all Subclasses, the only thing that changes is the Classname, so I thought there is no need to Override in each subclass. I have updated the code to reflect this. Please let me know if there is a better way of doing it/
Calling this.getClass() inside your search method will give you the concrete class of the current instance.
For example:
class Example
{
static class A {
public void search() {
System.out.println(getClass());
}
}
static class B extends A {}
public static void main (String[] args) throws java.lang.Exception
{
new A().search();
new B().search();
}
}
outputs
class Example$A
class Example$B
The cleanest way to do it is to override the method in each subclass.
interface Y {
void search();
}
class A implements Y {
public void search(){
search("A");
}
protected void search(String name) {
// implement your searching algoithm here
}
}
class B extends A {
public void search(){
search("B");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search();
}
}
That's the way inheritance is suppose to works. A super class should not know its subclasses.
And, in case you extends your class B, you can easily either:
-Keep the same behaviour as B:
class C extends B {
// do nothing, when calling search, it calls the method implemented in B
}
-Change the behaviour to search for "C"
class C extends B {
public void search(){
search("C"); // or search("whateveryouwant")
}
}
You can simply override the method in class B.
The other way could be to write the search() method as
void search() {
if (this.getClass().equals(B.class)) {
//The logic for B
} else if (this.getClass().equals(A.class)) {
//The logic for A
}
}
You have to provide the fully qualified name for the class.
Better follow template pattern.
interface Y {
void search(String name);
}
abstract class AbstractionTemplate implements Y{
#Override
public void search(String name) {
//a lot of code.
System.out.println("common stuff start");
doImplspecificStuffOnly();
System.out.println("common stuff end");
//a lot of code.
}
abstract void doImplspecificStuffOnly();
}
class A extends AbstractionTemplate{
#Override
void doImplspecificStuffOnly() {
System.out.println("a's stuff");
}
}
class B extends A {
#Override
void doImplspecificStuffOnly() {
System.out.println("B's stuff");
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
b.search("hey");
}
}

Thread and super keyword

The following code will output Program A. Kindly explain it w.r.t super.run();.
class RunnableA implements Runnable{
public void run(){
System.out.println("Program A");
}
}
class MyThread extends Thread{
MyThread(Runnable r){
//set as a target
super(r);
}
public void run(){
//System.out.println("MyThread");
super.run();
}
}
class Demo{
public static void main(String args[]){
RunnableA a1=new RunnableA();
//a1.start(); //Illegal
new MyThread(a1).start();
}
}
super.run(); means that MyThread's run() method executes Thread's run() method (which calls the run() method of the Runnable instance that was passed to the constructor).
Therefore new MyThread(a1).start(); executes RunnableA's run() method and prints "Program A".
In this example MyThread is quite useless, as it doesn't add any functionality to Thread. You can replace your main method with :
public static void main(String args[])
{
RunnableA a1=new RunnableA();
new Thread(a1).start();
}
and get the same behavior.

How to call a method defined while object instantiation?

wondering how it is possible to call public m method?
public class Test1 {
public static void main(String[] args) {
Test1 test = new Test1() {
public void m() {
System.out.println("m");
}
};
}
}
I don't believe you can. You'd have to create an interface or subclass. (Well, okay, that's probably not true. You could probably do it with reflection.)
E.g., like this (where you call it via test.m() after construction):
public class Test1 {
public static void main(String[] args) {
SubTest1 test = new SubTest1() {
public void m() {
System.out.println("m");
}
};
test.m();
}
private static abstract class SubTest1 extends Test1 {
public abstract void m();
}
}
Or like this, where it happens during construction:
public class Test1 {
public static void main(String[] args) {
SubTest1 test = new SubTest1() {
public void m() {
System.out.println("m");
}
};
}
private static abstract class SubTest1 extends Test1 {
public SubTest1() {
this.m();
}
public abstract void m();
}
}
You can't define an anonymous class constructor, so that last uses the constructor of the SubTest1 class and the abstract method.
You cannot directly invoke m since test is of type Test1 which does not contain a method called m, but you should never find yourself in a situation like this. The whole point of anonymous classes is to alter some already-existent aspect of the base class's functionality, so adding new methods makes no sense. Consider rethinking your design or using a named class instead.
Of course, if you won't care about test in the future you could do this:
new Test1() {
public void m() {
System.out.println("m");
}
}.m();
Although you would rarely want to do something like this, it could be useful if you're working with Thread or Runnable and need to invoke the run method.
If Test1 had a method called "m" you could just call test.m() after you instantiated the inner class:
public class Test1 {
public static void main(String[] args) {
Test1 test = new Test1() {
public void m() {
System.out.println("New Behavior");
}
};
test.m();
}
public void m() {
System.out.println ("Default Behavior");
}
}
Running this would output:
New Behavior

Dependency injection and Inheritance in Java

I have the following code:
public class GrandParent {
public void greet() {
System.out.println("Hello from grandpa.");
}
}
public class Parent extends GrandParent {
public void run() {
greet();
}
}
public class RunMe {
public static void main(String args[]) {
Parent p = new Parent();
p.run();
}
public void greet() {
System.out.println("Hi.");
}
}
I am tasked to write the class RunMe and as much as possible, I am not allowed to modify classes Parent and GrandParent. How can I implement this in such a way that when execution reaches run() of Parent, the greet() of RunMe (or it could be in another place) is executed and not the greet() of GrandParent.
Or is this possible in the first place?
I don't see how this is possible if you are to have a non-extended Parent object call a different greet method without changing Parent or Grandparent code.
You could write an instance (not static) inner class within RunMe that extends Parent and overrides Parent instance's run() such that it makes a call to the RunMe instance's run(). Your main() method would create an instance of the new subclass instead of Parent.
First, you need an instance of RunMe to invoke its run() method, since that isn't a static method. One way to hook into what's happening in Parent is to subclass Parent:
public static void main(String args[]) {
final RunMe runMe = new RunMe();
Parent p = new Parent() {
public void run() {
super.run(); // runs Parent.run()
runMe.run(); // runs the hook function
}
};
p.run();
}
I have no idea if this is what you're after.
try this:
public class MyParent extends Parent {
#Override
public void greet() {
System.out.println("hello from MyParent");
}
}
public class RunMe {
public static void main(String args[]) {
Parent p = new MyParent();
p.run();
}
}
I think you meant this:
public class RunMe extends Parent {
public static void main(String args[]) {
Parent p = new RunMe();
p.run();
}
public void greet() {
System.out.println("Hi.");
}
}

Categories