Need a design advice to skip object type casting-Collection of common programming errors

Assuming you really need this feature (Eran’s comment above raises a good point; polymorphism likely does much or all of what you need), the answer is generics. They’re a slightly advanced topic, but they’re central to Java (all of the collection classes in the JDK use them), so they’re very important to learn.

Generics are a way to say “some type,” and optionally “some type that’s a subtype of some other type.” The latter is what you want.

public class A
{
  private T b;

  protected T getB()
  {
    return b;
  }

  protected void setB(T b)
  {
    this.b = b;
  }
}

The part declares a generic parameter of T, and says it must be a subclass of B. From then on, you can use T as if it’s a type within the A class. For users of this class, they’ll have to specify what kind of A it is, and the compiler will automatically do the downcasting for you:

A a = new A();
a.set(new B1());
B1 b = a.getB();

Note that in the second line, if you had done a.set(new B2()) it would be a compile-time error: the compiler would complain that a is parameterized to B1, and therefore you can’t pass a B2 to it. At a very high level, you can imagine that the compiler is doing a search-and-replace, replacing T in the original class with B1. And if you had declared:

A a = new A();

then the search-and-replace would similarly turn T into B2.

In reality, it’s not quite that simple due to something called erasure. You can read more at the Java trail on generics, and there are lots of other resources available as well. This PDF is a good intermediate-level description.