197mz
197mz

Reputation: 7

Inheritance calling superclass method java

I have three classes: B inherits form A and C form B. I want to call fun2() method form B class. So the user is asked to input value of x and y and then in class C I want to display the user's imput calling fun2() method. The programm displays x=0 y=0 no matter what user's imput is. How can I access value of x and y in class C ?

import java.util.Scanner;

public class myClass{

    public static void main(String[] args) {

          C ccc = new C();
          ccc.fun3();
    }

}
class A
{
    Scanner in= new Scanner (System.in);
        int x, y;
        public void fun1()
        {
            System.out.println("x= ");
            x=in.nextInt();
            System.out.println("y= ");
            y=in.nextInt();
        }
}
class B extends A
{
    public void fun2()
     { 
        System.out.println("fun2");
        fun1();
    }

}
class C extends B
{
   B bb = new B();
    public void fun3()
    {
        bb.fun2();
        System.out.println("fun3");
        System.out.println("x= "+ x);
        System.out.println("y= "+ y);
    }
}

Upvotes: 0

Views: 63

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201537

Remove B bb = new B(); from class C. And change bb.fun2(); to super.fun2(); (and the super. is optional - because of the extends a C is-a B)

or print the x and y from bb (where you have set them, currently your fields in class C are not set - thus to display the values that were set, you would need to access them from bb).

System.out.println("x= "+ bb.x);
System.out.println("y= "+ bb.y);

Upvotes: 1

Related Questions