简体   繁体   中英

Why can't I use inherited objects in my inherited class?

    class Vehicle  // base class (parent) 
    {
      public string brand = "Ford";  // Vehicle field
      public void honk()             // Vehicle method 
      {                    
        Console.WriteLine("Tuut, tuut!");
      }
    }
    
    class Car : Vehicle  // derived class (child)
    {
      public string modelName = "Mustang";  // Car field
      brand = "WHY İS NOT ??? "; // Error.

  public void honk(); // Error.
}

Can't I do that? Does the class we inherit have its functions, methods, and variables? Did I learn something wrong?

Note; It works within the main function.

I've been dealing with this for a long time. : / (3+ hours)

You can't just write to a field (defined in a base class) from the derived class like:

brand = "WHY İS NOT ??? "; // Error.

...because you aren't definining a new field, rather you are attempting to change brand defined in the the base class Vehicle . Unfortunately the way it is written, the compiler thinks it's an orphaned assignment. It should exist in a in a method or constructor .

Try placing it in a constructor:

class Car : Vehicle  // derived class (child)
{
      public string modelName = "Mustang";  // Car field

      public Car()
      {
          brand = "Acme"; 
      }

      public void honk() {}
}

Honk

public void honk(); // Error.

The problem here is that your method has no body. Whilst you can do that in an interface you can't in a non-abstract method belonging to a class.

Give it a minimal one like so:

public override void honk() { }

...or:

public override void honk() 
{
   // same thing but formatted differently
}

Notice there is a new override . If you want a new implementation of honk in a derived class it's best to make the method virtual .

ie

class Vehicle  // base class (parent) 
    {
      // ...

      public virtual void honk()           
      {                    
        Console.WriteLine("Tuut, tuut!");
      }

      // ...
    }

Alternatively you can use new instead of override but there are gotchas .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM