Can a Class Have No Constructor

Can a class have no constructor?

It is not required to explicitly define a constructor; however, all classes must have a constructor, and a default empty constructor will be generated if you don't provide any:

public Maze() {
}

See Default Constructor.

Consequences of no constructor in java OOP

if there were no constructors in my class at all, what could I not do

  1. You cannot initialize your object's member variables using constructor parameters. In order to do that, you would need to use setX methods for nonpublic (protected, private) variables, or use dot notation if they are public.
  2. As a side effect of 1, you cannot have uninitialized final member variables

Having no constructor does not prevent you from instantiating the object as the default constructor will be made. You cannot just "remove" the default constructor to literally have no constructor.

What gets called when you initialize a class without a constructor?

There's no such thing as a "class without a constructor" in Java - if there's no explicit constructor in the source code the compiler automatically adds a default one to the class file:

public ClassName() {
super();
}

This in turn can fail to compile if the superclass doesn't have a public or protected no-argument constructor itself.

Why can I instantiate a class without a constructor in C#?

If you don't declare any constructors for a non-static class, the compiler provides a public (or protected for abstract classes) parameterless constructor for you. Your class effectively has a constructor of:

public TextStyle()
{
}

This is described in section 10.11.4 of the C# 4 spec:

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract, then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public.

The only classes in C# which don't have any instance constructors are static classes, and they can't have constructors.

Instantiating a class with no constructor

It might have an internal constructor. See this answer. This would mean you won't be able to access the constructor from a different assembly. (See MSDN.)

There might be some method in that assembly that instantiates an instance of that class. Try finding a method like that, and call it to get an instance of someClass.



Related Topics



Leave a reply



Submit