Is there a way to override class variables in Java?
Yes. But as the variable is concerned it is overwrite (Giving new value to variable. Giving new definition to the function is Override). Just don't declare the variable but initialize (change) in the constructor or static block.
The value will get reflected when using in the blocks of parent class
if the variable is static then change the value during initialization itself with static block,
class Son extends Dad {
static {
me = "son";
}
}
or else change in constructor.
You can also change the value later in any blocks. It will get reflected in super class
Java Inheritance: How to override instance variables/fields from parent class?
Your parent class instance variables are Private to that, so you can't update them from Child class. So rather you use parameterize method or create Protected setter/getter for instance variables (or protected variable itself). In you your case the variables are final so you actually can't even update them. So technically that's not possible to use child class variables in parent class.
If you update your variable to protected
and remove static/final
modifiers (as you mentioned in comments that you can). Before calling method from parent class, update variable data before calling super method. You can do it as below:
Approach 1 : Updating data in parent class before calling parent class method.
Parent Class:
public class ParentClass {
protected String firstName = "Billy Ray";
protected String lastName = "Cyrus";
protected int age = 58;
protected String city = "Hunstville";
public boolean methodIWantToReuse() {
// Passing in the objects created above as argument, which have the Parent
// instance variable data
Object1 obj1 = new Object(firstName, lastName);
Object2 obj2 = new Object(age,city);
Object3 obj3 = new Object(obj1, obj2);
Object4 obj4 = new Object(obj3);
return someRandomMethodHere(obj4);;
}
}
Child Class:
public class ChildClass extends ParentClass {
protected String firstName = "Miley";
protected String lastName = "Cyrus";
protected int age = 27;
protected String city = "Los Angeles";
public boolean methodIWantToReuse() {
// Update data in Parent class first
super.firstName = firstName;
super.lastName = lastName;
super.age = age;
super.city = city;
return super.methodIWantToReuse();
}
}
Approach 2 : If you want to use parameterized method to make it stateless, you can do it as below:
Parent Class:
public class ParentClass {
protected String firstName = "Billy Ray";
protected String lastName = "Cyrus";
protected int age = 58;
protected String city = "Hunstville";
public boolean methodIWantToReuse() {
return methodIWantToReuse(this.firstName, this.lastName, this.age, this.city);
}
public boolean methodIWantToReuse(String firstName, String lastName, int age, String city) {
// Passing in the objects created above as argument, which have the Parent
// instance variable data
Object1 obj1 = new Object(firstName, lastName);
Object2 obj2 = new Object(age,city);
Object3 obj3 = new Object(obj1, obj2);
Object4 obj4 = new Object(obj3);
return someRandomMethodHere(obj4);;
}
}
Child Class:
public class ChildClass extends ParentClass {
protected String firstName = "Miley";
protected String lastName = "Cyrus";
protected int age = 27;
protected String city = "Los Angeles";
public boolean methodIWantToReuse() {
// Update data in Parent class first
return super.methodIWantToReuse(this.firstName, this.lastName, this.age, this.city);
}
}
NOTE: It's not good practice to keep local variables name same as the class level variables. But kept it here same for just understanding.
Overriding member variables in Java ( Variable Hiding)
When you make a variable of the same name in a subclass, that's called hiding. The resulting subclass will now actually have both properties. You can access the one from the superclass with super.var
or ((SuperClass)this).var
. The variables don't even have to be of the same type; they are just two variables sharing a name, much like two overloaded methods.
Overriding a super class's instance variables
Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).
Inherited class variables when initialized are overriding own value setted by parent
Your problem here is super()
calls the parent constructor, which calls init(). The strName = "";
statement is then run inside the child class constructor after the super()
call.
strName
should be a protected
variable in the parent class if you want to set it up like that. Otherwise, you should just bite the bullet and manually initialize it in the constructor after the call to super();
That's the safest and most predictable way to do this.
Introducing new variable in anonymous class override
There's one instance of anonymous extension of class Foo
(the instance that foo
points to). so it should not be surprising that changes to the one instance are cumulative.
The variable foo
is a reference to a Foo
, and a Foo
does not have a test
member, so there's nothing to reference.
You can't write a cast to the class that does have atest
member, since it does not have a name you can utter.
You could probably get there with reflection.
This all seems exactly as expected with class hierarchies.
An anonymous subclass is just a subclass without a name that can appear in source code.
If you actually need access to test
then declare a named subclass instead of an anonymous one. Suitable choice of access modifiers will allow you to declare foo
suitably, e.g. as FooBar foo
if the subclass is called FooBar.
Related Topics
Number of Days Between Two Dates in Joda-Time
Using Setdate in Preparedstatement
Display Indeterminate Jprogressbar While Batch File Runs
What Is Web-Inf Used for in a Java Ee Web Application
String, Stringbuffer, and Stringbuilder
How to Convert Java String into Byte[]
What Causes "'Void' Type Not Allowed Here" Error
Setting Background Images in Jframe
Eclipse Exported Runnable Jar Not Showing Images
Unix Epoch Time to Java Date Object
Generate/Get Xpath from Xml Node Java
How to Maintain Jtable Cell Rendering After Cell Edit
Is There a Destructor for Java
How to Monitor the Computer's Cpu, Memory, and Disk Usage in Java
How to Get Current Moment in Iso 8601 Format with Date, Hour, and Minute
Jar Bundler Using Osxadapter Causing Application to Lag or Terminate
How to Derive Module Descriptor for Auto Generated Module Names in Java 9