Reputation:
I want to access fields of a class from base class in Java. I can do it in dot net. see the example:
public class a{
// here I want to read the value of name or f1 or f2 or every other field values from derived classes
}
public class b extends a{
public string name;
}
public class c extends a{
public string f1;
public string f2;
}
How to do it?
Upvotes: 1
Views: 965
Reputation: 312
What you should do in this case is to define abstract methods in your class a, which class b and c has to implement. You can then call these methods from a to obtain the values set by b and c.
public abstract class a{
// here I want to read the value of name or f1 or f2 or every other field values from derived classes
abstract String getName();
abstract String getF1();
abstract String getF2();
}
public class b extends a{
private String name;
@Override
public String getName() { return name; }
@Override
public String getF1() { return null; }
@Override
public String getF2() { return null; }
}
public class c extends a{
public String f1;
public String f2;
@Override
public String getName() { return null; }
@Override
public String getF1() { return f1; }
@Override
public String getF2() { return f2; }
}
Upvotes: 0
Reputation: 234875
You really don't want to do that as it defeats the idea of inheritance.
You can, however set up abstract functions that are implemented by derived classes. That's good programming style. Those functions can access member data in the derived and base classes.
Doing things like (i) using reflection and(ii) casting to derived classes are hacks and should be avoided. The reason being that changing a derived class should not trigger the necessity for changes in a base class.
Upvotes: 2
Reputation: 200296
You cannot read the fields your class doesn't own without explicitly naming the subclass. So, this is doable as follows:
((c)this).f1;
However, doing this would be a bad code smell: you are now tying an abstraction embodied by a
to one of its specific implementations/extensions. You should better rethink your design.
In Java it is a must that you name your classes using CamelCase and packages using lowercase, otherwise some quite bad name-resolution anomalies can happen. Not to mention any Java user getting totally lost reading your code.
Upvotes: 3