Java inheritance - java

So I've been trying to find the proper way to get what should be pretty straightforward inheritance to function (the way I want ;)) and I'm failing miserably. Consider this:
class Parent
{
public String name = "Parent";
public Parent() {};
public void doStuff()
{
System.out.println(name);
}
}
class Child extends Parent
{
public String name = "Child";
public Child()
{
doStuff();
}
}
I understand that Java doesn't do what I'd expect in this case as for some reason member variables aren't overridden the same way methods are but my question is what is the proper way to achieve the behavior I'd expect? I'd like my base class to contain some functions that operate on member variables provided/defined by a given subclass. I'd think get/sets could work, but then it destroys my ability to just call super() and have my base class do the construction needed making my subclasses contain a bunch of construction instead of isolating it to the base class.
Any constructive suggestions are welcome.

You can always replace a variable with getter, if you want such kind of 'variable-inheritance'. Not sure if 'variable-inheritance' ((c)) is a good design pattern in general, though.
class Parent {
public void doStuff() {
System.out.println(getName());
}
public String getName() {
return "Parent";
}
}
class Child extends Parent {
public Child() {
doStuff();
}
public String getName() {
return "Child";
}
}
Or you could have protected constructor in Parent class, taking the name to use.
edit
I wouldn't call it a 'hack'. And version with passing parameter into parent constructor can be pretty elegant too.
class Parent {
private final String name;
// don't let use to invoke this constructor, only for child classes
protected Parent(String name) {
this.name = name;
}
// public constructor for users
public Parent() {
this("Parent");
}
public void doStuff() {
System.out.println(name);
}
}
class Child extends Parent {
public Child() {
super("Child");
doStuff();
}
}
do you have any idea why Java seems to have abandoned the concept of inheriting member variables?
Java has abandoned a lot of C++ concepts (starting from infamous multiple inheritance), because they didn't add that much value to the language, but increased its complexity.
Although I don't have anything against variable-inheritance, I'm not suffering without this concept either. And personally, I like the language simple and clean.

Do you really need two different name variables for a single instance? Do you genuinely have the idea of an object having a "name-when-viewed-as-Parent" and a "name-when-viewed-as-Child"? If not, just have a single variable in the Parent class.
How would the Parent class know which variables are going to be provided by the child? If every subclass is going to have the same set of variables, why aren't they in the parent class?
If you could give a more concrete example of the problem you're trying to solve, it would make it easier to give a concrete answer.

The subclass variable name is shadowing the super classes variable of the same name. So when Child declares and assigns name it's another separate variable.
Instead, consider name to be a property of the parent inherited by the child and pass name as an argument to the Parent constructor. Then you would invoke super("Child") from the child constructor.
Also, as a public property, it should be final. Otherwise expose it via getters and setters.

You are correct in that you can't override members of the class. You can achieve this by making name protected and setting it in the constructor.
class Parent {
protected string name;
public Parent() { name = "parent"};
public doStuff() {
System.out.println(name);
}
}
class Child extends Parent {
public Child() {
name = "child";
doStuff();
}
}

What you are trying to do won't work in Java. In Java, attributes declared in a parent class are not overridden in a child class.
If you want polymorphic behavior, then you need to declare the attributes private, and declare corresponding getter methods in the parent class that you can override in the child class.
Alternatively:
class Child extends Parent {
public Child() {
name = "Child";
doStuff();
}
}
though #shoebox639's answer does this in a more elegant way that allows you to declare the attribute as final. (Mutable public attributes are not a good idea ...)

You don't need to redefine your member variable in the subclass. You can write your code as #Stephen C says
class Child extends Parent {
public Child() {
name = "Child";
doStuff();
}
}
In your post
I'd like my base class to contain some functions that operate on member variables provided/defined by a given subclass.
You will write your super class at first and at this stage your super class does not know about your subclass.

Related

Converting Class of an Object into a Child Class

Say I have the following classes
public abstract class Parent {
public Parent() {
//stuff here
}
}
public class Child extends Parent {
public Child() {
//stuff here
}
public void doSomething() {
}
}
Then I get an object from an array of Parents
public Parent[] parents = new Parent[5];
Parent tempParent = parents[0]
If this object is of the child class, I want to cast the tempParent into the child class in order to use "doSomething" without having to create a new object
if(tempParent.getClass == Child.class) {
tempParent = (Child) tempParent;
tempParent.doSomething();
}
This, however, does not work. I still get an error telling me that doSomething is not a function in the Parent class. Is there a way to do what I'm trying to do?
You need to use the correct TYPE on the LEFT hand side:
Child someChild = (Child) tempParent;
Note: this does not create a new Object.
There is no way of having
Parent whatever = (Child) tempParent;
do what you want to do (invoke a Child class method)!
You see, the compiler only cares about the "defined" type of your reference, it does not take into account that you most likely, at runtime, just "put" something into that reference that in deed is a Child instance!
to do what you want to do.
And note: do not compare objects using ==. You should prefer to call equals() instead. For Class objects == should work (most of the time), but still: get used to check for equality using equals().
I think you're trying to solve the issue from the wrong side.
Technically speaking you should do it like this.
public abstract class Parent {
public Parent() {
//stuff here
}
public abstract void doSomething();
}
public class Child extends Parent {
public Child() {
//stuff here
}
#Override
public void doSomething() {
// Write the code of doSomething specific to child.
}
}
A bit off topic but you might want to consider the following:
I think that the class representation of your code is bad.
I think that you should have 2 concrete classes Parent and Child that are composed or either inherit from a common interface. Even better use composition over inheritance.
https://en.wikipedia.org/wiki/Composition_over_inheritance
if you are able to modify the parent class, I would recommend that you make doSomething an abstract method and have the child class override it. that way, there is no need to cast in order to invoke it.
https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

java: inheritance questions about overriding methods

If the method in the parent class does not need a parameter, but the overriding method in child class needs one. Is it good practice to have a no use argument in the method in parent class?
//in parent class:
getFeature(String name){
return defaultFeature;
}
//in child class:
getFeature(String name){
return new Feature(name);
}
This method is used and only used in another method in parent class. So we have the same signature for parent and child classes. The real problem has two child classes with a little different implementation of getFeature.
Or is there a better way to accomplish this?
Is it good practice to have a no use argument in the method in parent class?
It depends. If the API design anticipates that subclasses will need the parameter even though the base class doesn't, and you want to ensure that the parameter version of the method can be called through a parent-typed reference:
Parent instance = new Subclass();
Feature f = instance.getFeature("foo");
...then you have to include the parameter in the parent class signature even though you don't use it in the implementation. You might also have the no-parameter version which always provides the non-parameter functionality:
class Parent {
public Feature getFeature() { // Maybe you'd want this, maybe not
return defaultFeature;
}
public Feature getFeature(String name) {
return this.getFeature();
}
}
class Subclass extends Parent {
#Override
public Feature getFeature(String name) {
return /*...*/;
}
}
But if you anticipate that subclass instances will only be used with subclass-typed references:
Subclass instance = new Subclass();
// ^^---------- note
Feature f = instance.getFeature("foo");
...then there's no reason for the parent class's getFeature to have it. Subclasses can add it as an overload:
class Parent {
public Feature getFeature() {
return defaultFeature;
}
}
class Subclass extends Parent {
public Feature getFeature(String name) {
return /*...*/;
}
}
It just means that Parent-typed references will be limited to the no-parameters feature of getFeature.
Actual you override and it is a misleading approach as the client of the classes will have to pass a String while this is used only in the child class :
child.getFeature("makeSenseArg");
parent.getFeature("notUsedArg");
You should overload the getFeature() method in the child class:
//in parent class:
getFeature(){
return defaultFeature;
}
//in child class:
getFeature(String name){
return new Feature(name);
}
You would not benefit any longer of the polymophism but it should probably not be an issue as these are two distinct behaviors.
Merging them in a single method signature is maybe not the best thing to do.
Note that if you really need to rely on overriding, you could annotate the parameter with #javax.annotation.Nullable.
It makes the API clearer for the class clients and in addition code analysis tools such as Sonar takes also these annotations into consideration.
This would give :
// parent class
Feature getFeature(#Nullable String name){
return defaultFeature;
}
Besides, if for the overrided method, the parameter is mandatory, you could even specify the "reverse" annotation (#javax.validation.constraints.NotNulll) :
//child class
Feature getFeature(#NotNulll String name){
return new Feature(name);
}
Clients would call them :
child.getFeature("makeSenseArg");
parent.getFeature(null);

What is the best practice in Java to set a constant required in subclasses?

I have the following situation:
A parent class has a function that depends on a constant. But the only valid place to define that constant is in subclasses (parent class cannot define the constant's value, but it can be used with the constant undefined in 99% of use cases - the constant is a default to use if a specific configuration element is missing).
However, I would like to enforce that any child class inheriting from that parent class must define the value for the constant, since any child classes have to be able to use the other 1% of functionality.
What is the best practice to implement this enforcement in Java, ideally at compile time? (clearly, at runtime, I can simply check if the constant is null/empty in the method using it).
My own solution was to implement a value-getter for the constant as an abstract method in the parent class, and call that in combination with the real setter in the constructor; something like this:
public class HelperClass1 {
private String myConstant;
public void setMyConstant() {} // implemented obviousy
public void myMethod() { // Called from ParentClass's methods
// Do something useful with myConstant
}
}
import HelperClass1;
public abstract class ParentClass {
ParentClass() {
HelperClass1.setMyConstant( getMyConstantValue() );
}
public abstract void getMyConstantValue();
}
public class ChildClass1 extends ParentClass {
public void getMyConstantValue() { return "BUZZ"; }
}
public class ChildClass2 extends ParentClass {
} // Fails to compile without getMyConstantValue()
However, (a) This implementation has a problem (I can't use ParentClass itself, since it's now abstract) without subclassing; and (b) since I'm not a Java developer, I'm afraid that this isn't the best or the most elegant solution. So I'd like to know if there's a best practices approach that improves on what I implemented.
Provide two constructors for the parent class:
One is a protected constructor which takes the constant as an argument.
The other is private constructor which can construct instances of the parent class without setting the constant.
Provide a factory method for the parent class which can call the private no-constant constructor.
Classes that want to get an instance of the parent class can call the factory method. But child classes that want to inherit from the parent class have to call the protected constructer, which can validate that a valid constant was passed.
public class ParentClass {
private final SomeClass myConstant;
protected ParentClass(SomeClass aConstant) {
if (null == aConstant) {
throw new IllegalArgumentException("...");
}
myConstant = aConstant;
}
private ParentClass() {
myConstant = null;
}
public static ParentClass getInstance() {
return new ParentClass();
}
}
public class ChildClass {
public ChildClass() {
super(new SomeClass(42));
}
}
This isn't perfect. Someone could write a child class that passes a bad constant to the superclass constructor, and it wouldn't actually fail until some code tried to construct an instance of the child class.

Java inheritance: Reducing visibility in a constructor vs inherited method

In the following code, the constructor of Child has reduced visibility from public to private, which is allowed. The inherited methods, such as test(), cannot have reduced visibility. Why does Java operate this way?
class Parent {
public Parent(){}
public void test()
{
System.out.print("parent test executed!");
}
}
class Child extends Parent{
private Child(){}
private void test(){
System.out.print("child test executed!");
}
}
Constructors are not inherited, so Child() doesn't override Parent().
As for the methods, if you have (if Child() were public)
Parent p = new Child();
p.test();
Had it been allowed, this would be invoking a private method. So narrowing the access while overriding is not permitted.
When extending a class you are stating that your class is an extension of the parent class ("IS-A" relationship). What this means is that your class will have all methods of your parent class. This is the same as implementing an interface in java except you gain the method definitions (and fields) from your parent and not just methods declared in the interface. In interfaces constructors are not present because they are not methods. Constructors are special as they belong entirely to the class they are declared on. They declare how to construct only themselves.
In order to construct an object you must know that objects class.
class A {
private message;
private A() {
message = "You created an A";
}
public A(String message) {
this.message = message;
}
public void printMessage() {
System.out.println(message);
}
public static A createAnA() {
return new A();
}
}
class B extends A {
public B() {
super("You created a B");
}
}
A anA = new B(); // This will work
A anotherA = new A(); // This is not allowed as the constructor is private
A yetAnotherA = A.createAnA(); // This works too
So when we constructed B we can say that it is an A. Even though the constructor A is private this is due the constructor not being a part of the interface. The only thing we are saying about B when we assign it to a field of type A is that it has the methods of declared in A. In this case printMessage and createAnA.
That is why you can make the constructor private without changing the definition of the class. Now, why are you not allowed to make the method private when overriding a parents signature. This comes to having varying definitions of the [class].method(). Let's say that you could make your method private. Let's say that you declared a printMssage in the B class. Your reasoning is that you want that method for your use only inside the method and you want your parents printMessage to be used when called externally. Now, you wrote a method like this in the B class.
public void adjustMessage(String additional) {
message = getMessage() + additional();
}
Which version of get message would be executed? Your private one or the public one of your parents? The Java dispatcher would of course choose the public one as it is the one declared in the interface. So we we look at this example we can see if you did make your method have different a lower privilege your method could never be dispatched too which would just make things confusing for the reader.
This is a very good question.

How to create an "abstract field"?

I know abstract fields do not exist in java. I also read this question but the solutions proposed won't solve my problem. Maybe there is no solution, but it's worth asking :)
Problem
I have an abstract class that does an operation in the constructor depending on the value of one of its fields.
The problem is that the value of this field will change depending on the subclass.
How can I do so that the operation is done on the value of the field redefined by the subclass ?
If I just "override" the field in the subclass the operation is done on the value of the field in the abstract class.
I'm open to any solution that would ensure that the operation will be done during the instantiation of the subclass (ie putting the operation in a method called by each subclass in the constructor is not a valid solution, because someone might extend the abstract class and forget to call the method).
Also, I don't want to give the value of the field as an argument of the constructor.
Is there any solution to do that, or should I just change my design ?
Edit:
My subclasses are actually some tools used by my main program, so the constructor has to be public and take exactly the arguments with which they will be called:
tools[0]=new Hand(this);
tools[1]=new Pencil(this);
tools[2]=new AddObject(this);
(the subclasses are Hand, Pencil and AddObject that all extend the abstract class Tool)
That's why I don't want to change the constructor.
The solution I'm about to use is to slightly change the above code to:
tools[0]=new Hand(this);
tools[0].init();
tools[1]=new Pencil(this);
tools[1].init();
tools[2]=new AddObject(this);
tools[2].init();
and use an abstract getter to acces the field.
How about abstract getter/setter for field?
abstract class AbstractSuper {
public AbstractSuper() {
if (getFldName().equals("abc")) {
//....
}
}
abstract public void setFldName();
abstract public String getFldName();
}
class Sub extends AbstractSuper {
#Override
public void setFldName() {
///....
}
#Override
public String getFldName() {
return "def";
}
}
Also, I don't want to give the value
of the field as an argument of the
constructor.
Why not? It's the perfect solution. Make the constructor protected and offer no default constructor, and subclass implementers are forced to supply a value in their constructors - which can be public and pass a constant value to the superclass, making the parameter invisible to users of the subclasses.
public abstract class Tool{
protected int id;
protected Main main;
protected Tool(int id, Main main)
{
this.id = id;
this.main = main;
}
}
public class Pencil{
public static final int PENCIL_ID = 2;
public Pencil(Main main)
{
super(PENCIL_ID, main);
}
}
How about using the Template pattern?
public abstract class Template {
private String field;
public void Template() {
field = init();
}
abstract String init();
}
In this way, you force all subclasses to implement the init() method, which, since it being called by the constructor, will assign the field for you.
You can't do this in the constructor since the super class is going to be initialized before anything in the subclass. So accessing values that are specific to your subclass will fail in your super constructor.
Consider using a factory method to create your object. For instance:
private MyClass() { super() }
private void init() {
// do something with the field
}
public static MyClass create() {
MyClass result = new MyClass();
result.init();
return result;
}
You have an issue in this particular sample where MyClass can't be subclassed, but you could make the constructor protected. Make sure your base class has a public / protected constructor also for this code. It's just meant to illustrate you probably need two step initialization for what you want to do.
Another potential solution you could use is using a Factory class that creates all variants of this abstract class and you could pass the field into the constructor. Your Factory would be the only one that knows about the field and users of the Factory could be oblivious to it.
EDIT: Even without the factory, you could make your abstract base class require the field in the the constructor so all subclasses have to pass in a value to it when instantiated.
Also, I don't want to give the value of the field as an argument of the constructor.
Is there any solution to do that, or should I just change my design ?
Yes, I think you should change your design so that the subclass passes the value to the constructor. Since the subclass portion of your object isn't initialized until after the superclass constructor has returned, there's really no other clean way of doing it. Sure, this'd work:
class Super {
protected abstract int abstractField();
protected Super() { System.out.println("Abstract field: " + abstractField); }
}
class Sub {
protected int abstractField(){ return 1337; }
}
... since the implementation of abstractField() doesn't operate on object state. However, you can't guarantee that subclasses won't think it's a great idea to be a little more dynamic, and let abstractField() returns a non-constant value:
class Sub2 {
private int value = 5;
protected int abstractField(){ return value; }
public void setValue(int v){ value = v; }
}
class Sub3 {
private final int value;
public Sub3(int v){ value = v; }
protected int abstractField(){ return value; }
}
This does not do what you'd expect it to, since the initializers and constructors of subclasses run after those of the superclass. Both new Sub2() and new Sub3(42) would print Abstract field: 0 since the value fields haven't been initialized when abstractField() is called.
Passing the value to the constructor also has the added benefit that the field you store the value in can be final.
If the value is determined by the type of subclass, why do you need a field at all? You can have a simple abstract method which is implemented to return a different value for each subclass.
I think you need a factory (aka "virtual constructor") that can act on that parameter.
If it's hard to do in a given language, you're probably thinking about it incorrectly.
If I understand you correctly: You want the abstract class's constructor to do something depending on a field in the abstract class but which is set (hopefully) by the subclass?
If I got this wrong you can stop reading ...
But if I got it right then you are trying to do something that is impossible. The fields of a class are instantiated in lexical order (and so if you declare fields "below", or "after", the constructor then those will not be instantiated before the constructor is called). Additionally, the JVM runs through the entire superclass before doing anything with the subclass (which is why the "super()" call in a subclass's constructor needs to be the first instruction in the constructor ... because this is merely "advice" to the JVM on how to run the superclass's constructor).
So a subclass starts to instantiate only after the superclass has been fully instantiated (and the superclass's is constructor has returned).
And this is why you can't have abstract fields: An abstract field would not exist in the abstract class (but only in the subclass) and so is seriously(!) "off limits" to the super (abstract) class ... because the JVM can't bind anything references to the field (cause it doesn't exist).
Hope this helps.

Categories

Resources