简体   繁体   中英

how to pass Class B variable to class A,if class A extends Class B

extending class B in Class A, now I am printing value of variable a in Class A.The result i am getting is a=0 . How can i get the value a=2

Class A

package testing;

public class ClassA extends ClassB {

    public void print(){
        System.out.println("a= " +a);
    }
    public static void main(String arg[]){
        ClassA ca = new ClassA();
        ca.print();

    }
}

Class B

package testing;

public class ClassB {
int a;
public void send(){
    a=2;
}
}

Initially the value of a is 0 , as you have not set it to anything, and by default, when you call new ClassA(); it is initialized to 0. Hence you get 0 as the output.

You need to call the send method, to set the value of a to 2 .

ClassA ca = new ClassA();
ca.send(); //Here
ca.print();

Another easier way to understanding of parsing of variables between classes is using the get-set methods.

Class A coding:

public class ClassA extends ClassB {    
public static void main (String [] args)
{        
    ClassB ClassBValue = new ClassB();
    System.out.println(ClassBValue.getA());
}   

}

Class B coding:

public class ClassB {
     int A = 2;       
    public int getA()
    {
        return A;
    }
    public void setAValue(int A)
    {
        this.A = A;
    }   
}

Hope this helps

You are calling ca.print() without assigning any value to it, so basically it is printing initialized value for int a which is 0.

Put a call to send() before the print function, Compiler will first check for function send in ClassA , when it does not find it there it will call send function of the SuperClass which is B, this will assign value '2' to your variable a, When you call print() , print function present in Class A is called, Now Class A has no variable called a, so the value of variable a is called from it's super class and you will get value of 2 printed.

Code should look like ->

    public class ClassA extends ClassB {

    public void print(){
        System.out.println("a= " +a);
    }
    public static void main(String arg[]){
        ClassA ca = new ClassA();
        ca.send();
        ca.print();

    }
}

public class ClassB {
int a;


public void send(){
    a=2;
}
}

Your int variables, by default, are initialized with 0.

Some options:

A) Alter your main method to call the send method

    ClassA ca = new ClassA();
    ca.send(); //set the value to 2
    ca.print();

B) If don't want to alter your main method (for any reason), you can move the variable initialization to the class construtor:

    ClassA() {
      a = 2
    }

Now, when you instantiate your the class (new ClassA()), 'a' gonna be equals 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM