Discard variables and methods

I have an abstract class that is extended to provide the standard methods and variables that I need. This time, however, I need to extend one class, but some variables and some methods do not help me. So I was wondering if it is useless to disable these variables / methods. I point out that I am forced to extend this class, I cannot create another. For example, I have this abstract class:

public abstract class A {
    protected int a, b, c;

    public abstract void A();
    public abstract void B();
    public abstract void C();
}

public class B extends A {
    public B() {
        a = 5;
        b = 7;

        A();
        B();
    }

    public void A() {
        System.out.println("A: " + a);
    }

    public void B() {
        System.out.println("B: " + b);
    }

    //Unset the variable 'c' and the method 'C()' because they are useless
}

Actually, I don’t know if this is worth doing, I rely on your knowledge.

+4
source share
4 answers

, , A B , A A.

,

public abstract class BaseClass {
    protected int a, b;

    public abstract void A();
    public abstract void B();
}

public abstract class A extends BaseClass {
    protected int c;

    public abstract void C();
}

public class B extends BaseClass {
}
+4

"" .

.

public abstract class A {
    protected int a, b;

    public abstract void A();
    public abstract void B();
}

public abstract class AC extends A {
    protected int c;

    public abstract void C();
}

A () , , , - , C().

@Override
public void C() {
  throw new UnsupportedOperationException("This method is not allowed for this class");
}

, javac C(), RuntimeException . , , - RuntimeException try...
, = P

. , , C() .

+2

, . /, , .

, , B, , :

public class B extends A {

    //c property is private.

    public B() {
        a = 5;
        b = 7;

        A();
        B();
    }

    public void A() {
        System.out.println("A: " + a);
    }

    public void B() {
        System.out.println("B: " + b);
    }

    //This is set as publicly inaccessible, although implementation is provided.
    private void C() {}
}
+1

Only you can do method chow abstract. Therefore, there is no need for implementation. if you need it in subsequent subclasses, you can use it

public abstract void C();
0
source

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


All Articles