Nick Peelman
Nick Peelman

Reputation: 583

setting value's of a superclass (inheritence)

I'm having some trouble setting the variables of a SuperClass

I have following classes:

    • Computer(SuperClass)
    • Laptop(SubClass)
    • Desktop(SubClass)
  • In the SupperClass Computer I have a variable string name;

    public class Computer
        {
            protected string name;
        }
    

    When I call the method ChangeName(string yourName) from the laptop class, it should set the variable name in the SuperClass Computer, like this:

    public class Laptop : Computer
    {
        public void ChangeName(string yourName)
        {
            name = yourName;
        }
    }
    

    When I try to get the name ,with properties, from the Superclass Computer, it returns Null. I debugged to see what happend, and the SubClass Laptop actually changed the name in SuperClass, but when the method ChangeName ended compiling, it was back restored to null.

    What may have caused this?

    Upvotes: 0

    Views: 381

    Answers (1)

    Shaharyar
    Shaharyar

    Reputation: 12449

    I think you are setting up the variable like

    laptop.ChangeName(name);

    and trying to get the name like

    computer.name.

    You are misunderstanding the inheritance.

    Obviously that will be null. Because computer and laptop are two different objects. Laptop is inherited but it doesn't mean that you can access computer object using laptop object.

    After setting up the values using laptop.ChangeName(name);. Print laptop.name and you will get the name you've set.

    Upvotes: 1

    Related Questions