Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Java code

Tags:

java

I am trying to understand what I am doing wrong with this code but I don't find the answer. Why it does not print anything in the compiler?

Please help. Thanks in advance.

public class ClassA {

     int x = 0;
     int y = 1;

     public void methodA() {

         System.out.println( "x is " + x + " , and y is " + y) ;
         System.out.println( "I am an instance of:  " + this.getClass().getName() ) ;
     }
}

class ClassB extends ClassA {

    int z = 3; 

    public static void main(String[] args) {

        ClassB obj1 = new ClassB();
        obj1.methodA();

    }
}
like image 913
user6527926 Avatar asked Apr 10 '26 15:04

user6527926


2 Answers

Because you are only compiling , not running the code. Run it. It will print the result to console for sure.

No Overriding concept there in your code as of now. Every Children is Parent. You'll have access to that method and it prints the implementation of Parent (ClassA).

Coming to the concept of Overriding, if you want to see the implementation of methodA() in ClassB, then you need to Override it in ClassB and provide implementation related to ClassB.

like image 192
Suresh Atta Avatar answered Apr 13 '26 05:04

Suresh Atta


I don't have any problems, everything works as it should. It prints:

x is 0 , and y is 1
I am an instance of:  test.ClassB

Process finished with exit code 0

Check your IDE.

like image 40
PaintedRed Avatar answered Apr 13 '26 04:04

PaintedRed