im a astudent @ LTHS, in my forst year of Java, how do i make a default, and non-default contructor, and how to they work?

Recommended Answers

All 4 Replies

A default constructor is one that takes no parameters and sets the initial values for the class.

public class CSomething
{
   public int iFred;

   public CSomething()
   { // default constructor
      iFred = 0;
   }

   public CSomething(int iSetFred)
   { //non-default
      iFred = iSetFred;
   }
}

A default constructor is one that takes no parameters and sets the initial values for the class.

Not exactly. Constructors can have arguments, or no arguments. If you do not create any constructors, the compiler gives you a "default" constructor which is a no-args constructor that simply calls the superclasses' no-args constructor.
Any constructor that you define explicitly is, by definition, not a "default constructor".

see: http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html

commented: Great explanation +6

A default constructor is one that takes no parameters and sets the initial values for the class.

public class CSomething
{
   public int iFred;

   public CSomething()
   { // default constructor
      iFred = 0;
   }

   public CSomething(int iSetFred)
   { //non-default
      iFred = iSetFred;
   }
}

so the default constructor just sets a value to a variable if the user has not already done so?

No. A default constructor just calls the superclasses' no-args constructor. If you want to do any special initialisation you need to write a constructor (which may or may not take arguments)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.