2

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();

    }
}
WilQu
  • 7,131
  • 6
  • 30
  • 38
user6527926
  • 55
  • 1
  • 3
  • 8

3 Answers3

10

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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.

PaintedRed
  • 1,398
  • 5
  • 19
  • 30
0

The class with main method should be 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() ) ;
     }
}

public class ClassB extends ClassA { int z = 3;

public static void main(String[] args) {
    ClassB obj1 = new ClassB();
    obj1.methodA();

}

}

This works

Sarfaraz
  • 45
  • 4
  • _The class with main method should be public_ No, this is not mandatory. A class which has a main method can be run even if it doesn't have an access modifier. – BackSlash Aug 06 '14 at 14:39
  • @BackSlash plz check this: http://stackoverflow.com/questions/12524322/what-if-main-method-is-inside-non-public-class-of-java-file – Sarfaraz Aug 06 '14 at 14:45
  • Please check this and try it yourself: http://ideone.com/Qlsq6m Look at the class definition. It's not declared as `public class`, it compiles and runs fine. – BackSlash Aug 06 '14 at 14:48
  • @BackSlash, I agree with you. We have to make sure we are executing the correct class (i.e. don't confuse it with the file name) – Sarfaraz Aug 06 '14 at 15:36