Search code examples
javasubclass

java extended class inheritance


Sum s = new Sum();
Sum.SetToZero z = new Sum.SetToZero();

Scanner input = new Scanner(System.in);
String read = input.nextLine();

while (!read.equals("end")) {

    if (read.equals("add")) {
        s.add()
    } 
    else if (read.equals("get")) {
        System.out.println(s.returnTotal());
    }
    else if (read.equals("zero")) {
        z.zero();
    }

   read = input.nextLine();
}

class:

public class Sum {

    int total = 0;

    public void add() {
        total += 1;
    }

    public int returnTotal() {
        return total;
    }

    public static class SetToZero extends Sum {

        public void  zero() {
            total = 0;
        }
    }
}

input:

add
add
zero
add
get
add
get
end

output:

3
4

output wanted:

1
2

Shouldn't the subclass inherit the total and set it to zero? What am I doing wrong? I know I could just move the zero into the main class but I want it to be in a separate class. thx for your help.


Solution

  • By making your total variable static, you can get the desired output.

    class Sum {
        static int total = 0;
        public void add() {
            total += 1;
        }
    
        public int returnTotal() {
            return total;
        }
    
        public static class SetToZero extends Sum {
            public void  zero() {
                total = 0;
            }
        }
    }