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();
}
}
Related
I'm toying around with instance control flow and static control flow, notice the code below
class A {
{
m1();
}
A(){
System.out.println("A constructor");
}
void m1(){
System.out.println("A m1");
}
}
public class Main extends A {
public static void main(String[] args) throws Exception {
Main m = new Main();
}
void m1(){
System.out.println("Main m1");
}
}
The output for the code is:
Main m1
A constructor
I know this is because:
First, static blocks and variables were identified top-to-bottom parent-to-child, in this case there was just a main() that was static. Second, the static blocks and variable assignments are executed, so main()'s execution starts, and there is an attempt to create a new Main object.
So third, the instance blocks and variables of parent class will be identified. Then they will be executed top-bottom. (After that the constructor of the parent class will run, then the instance blocks and variables of child class will be identified, following which they will be executed top-bottom and finally the child class' constructor will execute).
So the instance block inside A, calls `m1()`. Then, A's constructor executes. Finally, control flow is returned to `main()` and program terminates.
Now, the call to `m1()` from A invoked `m1()` of `Main`. However, had I made both the `m1()` methods static, everything else remaining same, the call to `m1()` from the instance block of A would then have invoked `m1()` of A.
I have two questions(Why? Purely for academic reasons, I'm still learning Java):
When both the m1() methods are non-static, is it possible to invoke A's m1() from the instance block of A? I tried doing a this.m1() but that still invoked Main's m1().(Why?)
When both the m1() methods are static, is it possible to invoke Main's m1() from the instance block of A? (I'm guessing no but I'm not certain).
I know in the first case, it's overriding taking place, and in the second case it's method hiding. But I'm still not sure how to answer my questions based on that knowledge.
After compilation is done java 8 compiler your code looks like this:
class A {
A() {
this.m1(); // at runtime this refers to Main class instance
System.out.println("A constructor");
}
void m1() {
System.out.println("A m1");
}
}
public class Main extends A {
public Main() { }
public static void main(String[] args) throws Exception {
Main m = new Main();
m.m1();
}
void m1() {
System.out.println("Main m1");
}
}
Now to answer your first question: No. You cannot unless you are creating an instance of A(actual object of A).
To your second question:
after making both m1's static compilation looks like this:
class A {
A() {
m1(); // resolves to A's m1
System.out.println("A constructor");
}
static void m1() {
System.out.println("A m1");
}
}
public class Main extends A {
public Main() {
}
public static void main(String[] args) throws Exception {
new Main();
}
static void m1() {
System.out.println("Main m1");
}
}
Now no matter which instance(A or Main) you create you will see A's m1 excuted.
1.(When two methods are instance method) If you are inside the A (parent) class, if you call m1(); or this.m1(); you will call the A version of the m1() method but if you are inside the main class (child), if you call m1(); you will call the main version of m1 although if you call super.m1(); you will be calling the A version of m1 method.
2.(If the methods are static) you can call each version wherever you want, without and object of a class, for example, you can invoke mainĀ“s m1 method inside the A block with the following line Main.m1(); // ClassName.StaticMethodName();
I was revising some of the old school concepts of Java in order to solve one problem . I have written the following code where i am trying the create objects of multiple class in that same classes and calling the methods with those objects from the main.
class a {
public void display() {
System.out.println("inside class a");
a a1= new a();
}
}
class b {
public void display() {
System.out.println("inside class b");
b b1= new b();
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a1.display();
b1.display();
o.display();
}
}
I am getting object cannot be resolved error. My question is what i need to change to let the above code work. And, do i need to always declare objects inside the main().
Any help will be highly appreciated
I'm not really sure why you would want to do that, but assuming you're just wondering about the possibility to implement such a thing - yes, it can be done.
You can create an instance of a class inside that same class, like so:
public class A {
public static A instance = new A();
public void display() {
System.out.println("inside class A");
}
}
Pay attention to the static modifier in the above code; it allows you now to access instance from another place (class, method, main) like so:
A.instance.display();
If you want to know whether you can declare a variable inside a method, and not a class, and make it accessible from another method, then the answer is - no, you cannot.
Yes you need to declare objects inside the main()
class a {
public void display() {
System.out.println("inside class a");
}
}
class b {
public void display() {
System.out.println("inside class b");
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
a a1= new a();
b b1= new b();
one o = new one();
a1.display();
b1.display();
o.display();
}
}
Don't know what you want to achieve and yes you should create object of class a and class b inside main functions to use instance methods of these classes.
package com.stack.overflow;
class a
{
public void display()
{
System.out.println("inside class a");
//a a1= new a(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
class b
{
public void display()
{
System.out.println("inside class b");
//b b1= new b(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
public class one
{
void display()
{
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a a1=new a();
b b1=new b();
a1.display();
b1.display();
o.display();
}
}
You may find the answer to your confusion easily - #ratul-sharker : a1 & b1 must be declared and instantiated inside the main. as well as other answers here correcting your code.
The real question is your notion of scoping and lifetime of variables - Not only a1 and b1 lie inside the classes a and b but they have been instantiated inside methods so they are local. So, try to understand the difference between field variables and local variables - their lifetimes and scopes are vastly different.
Accessing a local variable directly like that(which will be instantiated when the method is called) is like asking asking for a result from future in the present. Note that field variables will remain as long as object is alive but the local variables will remain only for the duration of the method call.
Hope it is clear to you now.
Also, your question:
My question was is it possible to create an object of an class in the
same class and call it from main?
Yes. Because main is a static method so it is not bound to an object like non-static method does. static methods are class level while non-static methods are object level. You can also create an instance in a non-static method for that matter.
I have a little confusion in Java overriding. Suppose we have the following inheritance:
class A{
public A(){
}
void show(){
System.out.println("SuperClass");
}
}
class B extends A{
#Override
void show(){
System.out.println("SubClass");
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
b.show();
}
}
Clearly, class B overrides the method show() that is inherited by the class A. Why is not b.show(); printing the message System.out.println("SuperClass"); as well since class B has now the method show() from class A?
Thank you.
The show method of class B overrides the show method of class A and doesn't call it, so there's no reason for System.out.println("SuperClass"); to be executed when you call show on an instance of B.
If you change class B to :
class B extends A
{
#Override
void show(){
super.show ();
System.out.println("SubClass");
}
}
calling show on an instance of B will also execute the logic of A's show method.
In class B you are overriding, in other words replacing the original implementation of the show() method. Every time you invoke show() on an object that is instanceof B that version of the method will be called.
The only way to refer to the original show() method is to refer to it using the super.show() syntax inside B or any other class that extends A.
And as an additional note, that #Override annotation is just to add additional compiler checks but it's not required to actually override a method, you just need to re-implement it as you have done in B.
its the matter of polymorphism which acts , i.e., method call to method body happens at run time i.e when JVM invokes B b=new B(); so B object is of type class B ,so the method it displays B's method which is overridden one, if you put super() in B()'s constructor you can get parents one.
This is the effect of overriding in inheritance. You just replace the method from the superclass (but you can still reach the old one!) Here I also added a little bit with polymorphism too. Hope that this will help you.
class A{
public A(){
}
void show(){
System.out.println("SuperClass");
}
}
class B extends A{
void superclass() {
super.show();
}
#Override
void show(){
System.out.println("SubClass");
}
}
public class Test {
public static void main(String[] args) {
B b = new B();
b.show(); //SubClass
b.superclass(); //SuperClass
A a = new A();
a.show(); //SuperClass
A c = new B();
c.show(); //SubClass
//c.superclass(); //error! the program won't compile
}
}
Example:
class MainClass {
public doIt() {
...
else doIt();
}
}
class SubClass extends MainClass {
#Override
public doIt() {
super.doIt();
...
}
}
Now the problem is:
I call SubClass.doIt()
MainClass.doIt() is called
MainClass.doIt() makes recursion calling doIt()
But: the SubClass.doIt() is called instead of MainClass.doIt()
That is very strange behaviour and problems are programmed! I tried to call the recursion with this.doIt() but that didn't help.
Someone has an idea?
Thanks alot for your answers, this problem is solved.
That's the supposed behavior, by not setting a method final, that means it can be overriden, so you must always take into account someone can do this. Call's to that method are never guaranteed to be to the method at that level.
You can however solve this problem elegantly, by using a (protected) final method:
class MainClass {
protected final void innerDoIt () { //final: so no #Override
...
else innerDoIt();
}
public void doIt() {
innerDoIt();
}
}
And then:
class SubClass extends MainClass {
#Override
public doIt() {
super.doIt();
...
}
}
final ensures, the method can't be overriden. So at that moment, you have a contract (guarantee) that the innerDoIt method is indeed the innerDoIt method you think it is.
So in case you don't wan't the caller to get overriden, simply hedge it into another final method. By making it protected, that method can also be called by the SubClass.
public class Main {
public static void main(String[] args) {
B b = new B();
b.doIt();
System.out.println();
A a = new B();
a.doIt();
}
public static class A{
boolean check=false;
public void doIt(){
System.out.println("A start");
if(check){
}
else{
check = true;
doIt();
}
System.out.println("A end");
}
}
public static class B extends A{
#Override
public void doIt() {
System.out.println("B start");
super.doIt();
System.out.println("B end");
}
}
}
In this example, both b and a are instances of class B, so as you probably expect, a.doIt() and b.doIt() will output the same result.
B start
A start
B start
A start
A end
B end
A end
B end
B start
A start
B start
A start
A end
B end
A end
B end
When you call doIt(), you are implicitly calling this.doIt(), and this is an instance of class B. There is no syntax to do what you want do without seperating the content of doIt() (see CommuSoft's answer)
what will be the flow of execution in case of override? What i believe is , when we call a constructor/object of any class, during execution first it call parent constructor and than child. but what will happen in case of over ridding?
lets suppose:
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
Out put of this code is:
In Class b
In Class b
what i don't understand is, why it's printing "In Class be" only, it should be "In class A and, In Class b",
when i remove override method from class b. it give me desired output.
All java methods are virtual. It means the method is called with using actual type of this. So inside of constructor A() {} this is the instance of B, so that is why you've got its method call.
Calling like this printStatus() will call the method from the same class. If you call with super.printStatus() it will envoke method from the super class (class which you have extended).
When you over-ride a method you over-ride it completely. The existence of the original implementation is completely invisible to other classes (except via reflection but that's a big topic of its own and not really relevant). Only your own class can access the original method and that is by calling super.methodName().
Note that your class can call super.methodName() anywhere, not just in the overriding function, although the most usual use for it is in the overriding function if you want the super implementation to run as well as your own.
Constructors are a slightly special case as there are rules about how and why constructors are called in order to make sure that your super-class is fully initialized when you try and use it in the inheriting class.
super is always called whether you write super(); or not.
In the example printStatus() method of Class A will never be called. Since you are creating an instance of class B and there will be method overriding. You can use the following to call the Class A printStatus() method.
public B()
{
super.printStatus();
}
When you override a method, it will override the one that you expect from class A.
Should use super keyword for calling super class method.
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
Constructor public B(){ super.printStatus(); } calls Class A print method and constructor public A(){ printStatus(); } calls Class B print method since you've overridden.
But its wrong with overridable method calls in constructors.
Try with like this :
class A {
public A(){
printStatus();
}
public void printStatus(){
System.out.println("In Class A");
}
}
class B extends A{
public B(){
super.printStatus();
printStatus();
}
#Override
public void printStatus(){
System.out.println("In Class b");
}
}
public class Test2 {
public static void main(String[] args){
B b = new B();
}
}
For better understanding the concepts of Overloading and Overriding just go through this links:
http://en.wikibooks.org/wiki/Java_Programming/Overloading_Methods_and_Constructors