How can I override my instance variable of array type

Click For Summary

Discussion Overview

The discussion revolves around the challenges of overriding an instance variable of array type in a class hierarchy involving inheritance in Java. Participants explore various approaches to managing the visibility and initialization of an array member variable in a base class and its subclasses, focusing on the implications of encapsulation and method overriding.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Conceptual clarification

Main Points Raised

  • One participant describes an inheritance problem where a subclass attempts to override an array variable defined in a base class but ends up hiding it instead.
  • Another participant suggests initializing the array in the subclass constructor to avoid hiding the base class variable.
  • A different viewpoint critiques the naming convention of the classes, suggesting that the relationship between Parent and Child may need reconsideration.
  • One participant proposes making the array variable protected to allow access from subclasses while preventing external modification.
  • Another participant offers an alternative design where the Parent constructor accepts an array to initialize the labels, allowing for flexibility in subclasses without needing to override the method unless necessary.
  • Some participants discuss the implications of the abstract method getLabels() and its necessity in subclasses, emphasizing the importance of ensuring it is implemented to avoid runtime errors.
  • A later reply questions the need for manual array copying in the constructor, suggesting a more straightforward approach to assignment.

Areas of Agreement / Disagreement

Participants express differing opinions on the best approach to manage the array variable and the class hierarchy. There is no consensus on a single solution, as multiple competing views on design and implementation remain present throughout the discussion.

Contextual Notes

Some participants note limitations regarding variable visibility and encapsulation, as well as the potential for NullPointerExceptions if the array is not properly initialized. The discussion also highlights the need for careful consideration of class relationships in object-oriented design.

walnutTree
Messages
5
Reaction score
0
Hi All,

Sorry to bother anyone, but I have run into a inheritance problem.
I have a base class which contains a member variable of array type, and an abstract method. Subsequently I created a sub class which derived from the base class. And I provide implementation for the abstract methods in the parent class. And I would like to override my array variable in the sub class, and use it as return value of .


Is there any way to able to override my variable?

here is my base class

Code:
public abstract class Parent{
	String[] labels;
	public Parent()
		{
			getLabels();
		}
	public abstract String[] getLabels();
}


and the following code contains the sub class with the main function:

Code:
public class Child extends Parent{
	String[] labels ={"name", "nickname", "birth"};
	public String[] getLabels()
	{
	   System.out.println("labels:  " + labels);	
	   return labels;	
	}
	
	public static void main(String[] args)	
	{
		new Child();
	}
}
 
Technology news on Phys.org
Hi Walnut
Code:
String[] labels ={"name", "nickname", "birth"};
is hiding Parent's version of labels you can't access it from Child. What you can do is initialize it in the constructor
Code:
public class Child extends Parent{
	Child()
	{
	labels = new String[]{"name", "nickname", "birth"};
	}
}
 
Last edited:
walnutTree,

Your extension of Parent is a bit odd. You are effectively saying that all children are parents. You might want to rethink your class names or what you're trying to do.

The other danger in the code is the lack of private, protected or public for your labels variable. Global class variables should never be public unless there is a need. In this case, if you should make it protected in your Parent class. Then you can set it in the Child constructor like genepool showed in his second code block.
 
Hi guys,

Sorry for my late reply I was busy.
Thanks your answers or suggestions, these were quite useful. If I remove the getLabels() line from the Parent's constructor and initialize it in the Child constructor, it will works properly.

Parent:
Code:
public abstract class Parent{
	String[] labels;
	public Parent() {}
	public abstract String[] getLabels();
}

Child:
Code:
public class Child extends Parent{
	public Child()
		{	
		 labels = new String [] {"name", "nickname", "birth"};
		 getLabels();
		}
	public String[] getLabels()
		{
 	   		System.out.println("labels:  " + labels.length);	
			return labels;	
		}
	public static void main(String[] args)	
		{
		new Child();
		}	}

But I would like to leave that line in the Parent's constructor, because I want to create more subclasses with the different content of labels array.

e.g.

  • - labels = { "name", "birth"}
  • - labels = { "name, "birth", "color"}

Therefore I'm afraid I forget to call the getLabel() function from every subclass. I would be happy if child subclasses could inherit the getLabel() methods from the Parent.
Is there any way to achieve this?

Thanks in advance for your help
 
I haven't done any Java in awhile, but I'm a bit confused by your code, this seems more logical to me:

Code:
public abstract class Parent
{
	// this variable is not accessible by the Child class, but each time you instantiate a Child, it will have it's own copy of this variable available via the public methods.
	private String[] labels;

	// the Parent constructor fills the label array
	public Parent(String[] newLabels)
	{
		labels = new String[newLabels.length()];

		for(int i = 0; i < newLabels.length(); i++)
		{
			labels[i] = newLabels[i];
		}
	}

	// this method returns the label array
	public String[] getLabels() { return labels; }
}

public class Child
{
	// the Child constructor calls the Parent constructor to fill the array it can't see
	public Child(String[] newLabels)
	{
		super(newLabels);
	}

	// the getLabels() function is inherited by the Child class, you don't have to override it to use it.

	public static void main(args[])
	{
		// declare a temp array to hold your labels
		String[3] labels = {"name", "nickname", "birth"};

		// instantiate a Child class and give it the labels
		Child myChild = new Child(labels);

		// this is a temp array to hold the labels that are returned.
		String[3] get_the_labels = myChild.getLabels();

		// print the labels
		for(int i = 0; i < get_the_labels.length(); i++)
		{
			System.out.println("label "+i+" : "+get_the_labels[i]+"\n");
		}
	}
}
 
Last edited:
If your getLabels() method will always return the labels array of strings then I can't see why you would not do it the easy way as Adyssa has done and placed the getLabels() method in the parent class. That way you only need to override it if it will return something different.

As Borg pointed out though, your hierarchy might need some revisiting. What you are saying is that a child is-a parent. It might be better for example that a parent is-a person, a child is-a person and a child has-a parent?
By your Child class extending your Parent class you are saying that a Child is a type of a parent.
 
walnutTree,

You're current code is about as clean as you can get it. Your abstract getLabels() method will guarantee that you have to implement it in every class that extends Parent. You won't be able to forget it because the code will break and the error will tell you about it. Also, if you forget to set the String array variable, you'll get a NullPointerException when you try to do anything it.

Again, I would make the labels variable in the Parent class a protected variable. That way you can set it from the child but you can't accidently change it from another class. Those types of errors can be hard to diagnose sometimes.

You could pass the labels into the parent as Adyssa has done but, the code inside of Adyssa's Parent constructor is completely unnecessary. If you wanted to pass in the array to the constructor, you would just do this:
labels = newLabels;
 
Oh that's true, I don't know why I copied the array manually! >.>
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 34 ·
2
Replies
34
Views
4K
Replies
8
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 9 ·
Replies
9
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
2
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 23 ·
Replies
23
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K