Overriding Fields or Properties in Subclasses

Overriding fields or properties in subclasses

Of the three solutions only Option 1 is polymorphic.

Fields by themselves cannot be overridden. Which is exactly why Option 2 returns the new keyword warning.

The solution to the warning is not to append the “new” keyword, but to implement Option 1.

If you need your field to be polymorphic you need to wrap it in a Property.

Option 3 is OK if you don’t need polymorphic behavior. You should remember though, that when at runtime the property MyInt is accessed, the derived class has no control on the value returned. The base class by itself is capable of returning this value.

This is how a truly polymorphic implementation of your property might look, allowing the derived classes to be in control.

abstract class Parent
{
abstract public int MyInt { get; }
}

class Father : Parent
{
public override int MyInt
{
get { /* Apply formula "X" and return a value */ }
}
}

class Mother : Parent
{
public override int MyInt
{
get { /* Apply formula "Y" and return a value */ }
}
}

If you overwrite a field in a subclass of a class, the subclass has two fields with the same name(and different type)?

Member variables cannot be overridden like methods. The number variables in your classes Beta and Gama are hiding (not overriding) the member variable number of the superclass.

By casting you can access the hidden member in the superclass.

In C#, why doesn't a subclass field's default value override the superclass field's default value?

Your code is shadowing the field, not overriding it.

It's the equivalent of this code:

class Bar : Foo
{
public new string a = "y";
}

Your compiler should have given you a warning on this code.

Now, since you're shadowing it means that in a call to A the field in Foo is used and it's like the field in Bar doesn't exist.

You can't override a field, but if you change the field to a property then you can do this:

class Foo
{
public virtual string a { get; set; } = "x";

public string A()
{
return a;
}
}

class Bar : Foo
{
public override string a { get; set; } = "y";
}

Now your code would behave as you first thought it would:

void Main()
{
Console.WriteLine(new Foo().A()); //x
Console.WriteLine(new Bar().A()); //y
}

Override Property in Subclass from Baseclass Interface

You should make the property implementation virtual in the base class, and put override instead of new on the implementations in derived classes. This should fix the problem.

Currently, the only class that provides the implementation for the property Info from the interface Inf is your BaseClass. According to your code, compiler thinks that the derived class SubClass introduces a new property with the same name, which is legal. Such property would be accessible only when you use the class directly, not through an interface.

Override property in Swift subclass

Let’s reduce the example:

class BaseClass {
var surname: String? {
didSet { print("BaseClass \(surname)") }
}
}

class SubClass: BaseClass {
override var surname: String? {
didSet { print("SubClass \(surname)") }
}
}

Then:

let object = SubClass()
object.surname = "Jones"

Will produce:

BaseClass Optional("Jones")

SubClass Optional("Jones")

The above is not overriding the stored property, surname, with another stored property. There is only the stored property of the base class and the subclass is simply adding its own observer to this property. I refer you to The Swift Programming Language: Inheritance: Overriding, which says:

Overriding Property Observers


You can use property overriding to add property observers to an inherited property. This enables you to be notified when the value of an inherited property changes, regardless of how that property was originally implemented.

In your example of name, you are overriding the computed property with the subclasses’ own computed property. Likewise, in your example of telephoneSet, you are also overriding the method with the subclasses’ own method. But with surname, you’re not overriding the base classes’ property, but merely letting the subclass add an observer to the base classes’ stored property.

Confusion Regarding Overriding Class Properties in Swift

You are so close to being there, except that you can't override a static property in a subclass — that is what it means to be static. So you'd have to use a class property, and that means it will have to be a computed property — Swift lacks stored class properties.

So:

class ClassA {
class var thing : String {return "A"}
func doYourThing() {
print(type(of:self).thing)
}
}
class ClassB : ClassA {
override class var thing : String {return "B"}
}

And let's test it:

ClassA().doYourThing() // A
ClassB().doYourThing() // B

Kotlin - Class Inheritance; Overriding properties

You should be getting a compiler warning. You should never use open properties or functions at construction time (in init blocks or property declarations), because it causes this kind of unwanted behavior. It's just about the only way you can get a NullPointerException in Kotlin without using !!.

The reason it happens is that the superclass's constructor (which includes init blocks and property declarations) is run before the subclass. Since you override the property name in the subclass, the backing field of the property name has not yet been initialized by the time init of the superclass is called, so the property returns the default Java field value of null. In the case of speed, the field type is a Java primitive int so its default value is 0.

Note that in your specific example, there was no need to override these properties because you are passing these values to the superconstructor anyway. You could remove the open keyword before the properties and declare your Dog like:

class Dog(
name: String,
speed: Int,
): Animal("Dog", name, speed) {}

Then it will behave properly.

Override a field in parent class with property in child class

The line self.x = val in the A.__init__ method will simply invoke your C.x setter. You already have everything handled here. You are handling per instance attributes here, not attributes on a class that are inherited by subclasses.

All you need to do is to set a different attribute in the setter to represent the x value. You could name it _x, for example:

class C(A, B):
_x = None

@property
def x(self):
if self._x is not None:
return self._x
return self.a + self.y

@x.setter
def x(self, val):
self._x = val

Note that if all C.__init__ does is call super().__init__, you don't need it at all. However, you do need to make sure at least A.__init__() plays along in the inheritance structure; add in more calls to super().__init__():

class A(object):
def __init__(self, val, *args, **kwargs):
super(A, self).__init__(*args, **kwargs)
self.x = val
self.y = 42

class B(object):
def __init__(self, *args, **kwargs):
super(B, self).__init__(*args, **kwargs)
self.a = 22

Using *args and **kwargs allows these methods to pass on any extra arguments to other classes in the hierarchy.

Demo, using the above classes:

>>> c = C(None)
>>> c.x
64
>>> c.x = 15
>>> c.x
15

Overriding Properties with Attributes

Assuming Name virtual on Parent:

public class Parent 
{
public virtual string Name
{
get { return this.name; }
set { this.name = value != null ? value.trim() : null; }
}
}

You can always do this:

public class Son : Parent 
{
[SonAttribute]
public override string Name
{
get { return base.Name; }
set { base.Name = value; }
}
}

If the Name property is not virtual you'll be creating a new property which hides the property on the base type, which is probably not what you want. See Knowing When to Use Override and New Keywords (C# Programming Guide) for details.



Related Topics



Leave a reply



Submit