Masriyah
Masriyah

Reputation: 2505

Referencing a class that inherits from another class

I am creating a library and i am referencing from class Main which inherits from Body

public class Main:Body

i added Main to my using references but when i go to initiate an instance - i tried:

Main _main = new Main() it underlines new Main() saying that it doesn't contain a constructor that takes 0 arguments.

How can i properly adjust that so i am referencing the class - do i need to included the inherited class as well?

Upvotes: 1

Views: 61

Answers (1)

jason
jason

Reputation: 241601

Main _main = new Main() it underlines new Main() saying that it doesn't contain a constructor that takes 0 arguments.

It's telling you exactly what the problem is. There isn't a public constructor on Main that takes zero arguments.

You need to do one of the following:

  1. Add a public constructor that takes zero arguments: public Main() { }.
  2. Invoke a different constructor that is public on the Main class: if the signature is public Main(object o) then you'd say Main _main = new Main(o) where o is some object.

Let's look at an example:

class Foo {
    public Foo() { }
}

This class has a public constructor with zero arguments. Therefore, I can construct instances via

Foo foo = new Foo();

Let's look at another example:

class Bar {
    public Bar(int value) { }
}

This class does not have a public constructor with zero arguments. Therefore, I can not construct instances via

Bar bar = new Bar(); // this is not legal, there is no such constructor
                     // the compiler will yell

But I can say

Bar bar = new Bar(42); 

Here's one more:

class FooBar { }

This class does have a public constructor with zero arguments. It does because if you do not provide any constructors, the compiler will automatically provide a public constructor with zero arguments by default. Thus, this is legal:

FooBar fooBar = new FooBar();

Upvotes: 3

Related Questions