Bidisha
Bidisha

Reputation: 297

TypeCasting to SubClass in Java

I have to typecast an java object to subclass because need to set a indicator on a method available in the subclass then I am going to set the Super class object in a List.

Do I need to to do anything in between or the indicator as set after typecasting is going to reflect when I get the object out from the List ?

MemRow is the Superclass and MemAttrRow is the Subclass with new property recstat; The code is below:

  MemRow memRow;
   List<MemRow> memRwList;//where the superclass will get added 
   // type cast to subclass memAttrRow and set the recstat
     MemAttrRow memAttrRow = (MemAttrRow) memRow;
     String ind= "A";
     memAttrRow.setRecStat(ind);
  //add superclass to the list
     memRwList.addRow(memRow);

Upvotes: 0

Views: 187

Answers (1)

pkalinow
pkalinow

Reputation: 1741

You don't need to do anything else. Assuming the memRow is really an instance of MemAttrRow, when you set its property it is going to be preserved during operations like adding the object to a list.

However, it is worth to be mentioned that you need to be sure that the real (runtime) type of an object is MemAttrRow before you type cast it or you can get ClassCastException.

Upvotes: 1

Related Questions