Abstract and concrete classes - getters and setters

434 Views Asked by At

How can I use setters in the concrete class? I have two abstract classes and the bottom concrete class should be able to set all the private variables I have the abstract classes, how can I do that? I could just add getters and setters in my concrete class, but because I have 4 derived classes from my second abstract class, I don't want to have duplicate code and a long list of public properties, any way to resolve that?

I am working in C#

2

There are 2 best solutions below

0
On

Using the protected keyword in c# you can access the variables in parent objects Like this

public abstract class Parent {
    protected int integer {get;set;}
}
public class Child : Parent {

    public Child(int value) {
        integer = value;
    }
    public int getValue() {
        return integer;
    }
}

see : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected

2
On

From Microsoft documentation :

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class, or in a class that is derived from that class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly.

private protected
The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.

So doesn't matter if the class is abstract or not, private can only be accessed within the same class.