Glide
Glide

Reputation: 21245

Type-check in method of child class

In Java, I have parent class P and a child class C.

In an abstract class, I have a method void blah(P parent). In a child class of the abstract class, it doesn't compile by having void blah(C child).

How do I achieve the type check in the child class?

Upvotes: 1

Views: 249

Answers (2)

Eshan Sudharaka
Eshan Sudharaka

Reputation: 607

I suggest you to use parent type parameter instead having the child parameter. If you use it you can pass any implementation or you abstract class and it will make you code reusable.

In your case you have two different methods and which is not an overridden method.

Upvotes: 1

Kleenestar
Kleenestar

Reputation: 799

void blah(P parent) and void blah(C child) are actually different methods. That's why you can not use the C Child to override an abstract P parent method.

So, in your child class of the abstract class, you can either

void blah(P parent){
  if(parent instanceof C){
     ...
  }else if(parent instanceof C2){

  }
}

Or just implement these two methods separately.

Upvotes: 4

Related Questions