Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset variables and methods

Tags:

java

I have an abstract class that is extended to provide standard methods and variables that I need. This time, however, I have to extend the same class but some variables and some methods do not serve me. So I was wondering if it was possible to turn off these variables / methods useless. I specify that I'm forced to extend this class, I can not 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 do not know if it's worth it to do it, I rely on your knowledge.

like image 563
mikelplhts Avatar asked Mar 17 '23 14:03

mikelplhts


2 Answers

This is bad behavior and it is advised to split your class hierarchy by pulling the common members of A and B in a new abstract super class and letting the rest which is specific to the class hierarchy of A in A.

This leeds to a situation similar to

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 {
}
like image 59
Smutje Avatar answered Mar 27 '23 20:03

Smutje


There is no built-in mechanism to 'unset' a variable or a method of a superclass.

The standard solution is to create two base class.

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 (terrible) workaround, which only works with method, could be to implement something like the below code to forbid the use of C().

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

Long story short, javac will accept the use C(), but a RuntimeException will be released on runtime. This exception will produce a crash if not catched, but because of the nature of RuntimeException, the compiler doesn't need a try statement...
Well, that's just an ugly piece of code =P

A cleaner workaround was proposed by Nick L. on another response, consisting to set C() as private.

like image 28
NiziL Avatar answered Mar 27 '23 21:03

NiziL