In Java, how to pass a subclass variable without declaring this variable in the parent class?

public class MyTest {
    public static void main(final String[] args) {
        B b = new B();
        b.print();
    }
}

class A {
    private final int x = 5;

    protected int getX() {
        return x;
    }

    public void print() {
        System.out.println(getX());
    }
}

class B extends A {
    private final int x = 10;

    @Override
    protected int getX() {
        return x;
    }


}

In this example, I need to print the value of a subclass in the parent class. It is working fine. No problems. Now this is print 10. But I do not want to define this property in the parent class A.

Because in this example, this data type is xvery simple. So no problem. But in real time, I want to use a different data type, which may be another class variable or List<something>that have huge data.

class A. . . , , , . .

+4
3

A getX(); .

public class Test {
    public static void main(final String[] args) {
        B b = new B();
        b.print();
    }
}

abstract class A {

    protected abstract int getX();

    public void print() {
        System.out.println(getX());
    }
}

class B extends A {
    private final int x = 10;

    @Override
    protected int getX() {
        return x;
    }
}

toString

@Override
public String toString() {
    return String.valueOf(getX());
}

public class Test {
    public static void main(final String[] args) {
        B b = new B();
        System.out.println(b);
    }
}

abstract class A {

    protected abstract int getX();

    @Override
    public String toString() {
        return String.valueOf(getX());
    }
}

class B extends A {
    private static final int X = 10;

    @Override
    protected int getX() {
        return X;
    }
}

x

, , , A .

, , ,

public class Test {
    public static void main(final String[] args) {
        B b = new B();
        System.out.println(b);
    }
}

interface MyInterface {
    int getX();
}

abstract class A implements MyInterface{
    @Override
    public String toString() {
        return String.valueOf(getX());
    }
}

class B extends A {
    private static final int X = 10;

    @Override
    public int getX() {
        return X;
    }
}
+3

getX , , .

abstract abstract. , .

A - ( /), . .

+2

, , getX() , print() . getX() .

+1

Source: https://habr.com/ru/post/1686897/


All Articles