Unit 2 (Prog 5) : Constructors in java

By | June 5, 2013

Constructor Demo code…

/*
 * 1. Constructor can use any return type.
 * 2. Constructor name must match the name of class.
 * 3. constructor must not have a return type.
 * 4. If you see a method with return type having same name as class than it is just a method.
 * 5. if you’ve typed in a constructor with arguments, 
 *  you won’t have a no-arg constructor unless you type it in yourself!
 * 6. Interface do not have constructors.
 * 7. constructors are never inherited.
 */
class DemoClass{
          String demoString;
          DemoClass(String value){
                    this.demoString = value;
          }
}
class ChildDemo extends DemoClass{
          ChildDemo(){
          // super(); // Error here, no default constructor found in super class.
                    super(“from child”); // now compiler feels good.
          }
// more code…
}
// check out what happens after removing comments from following declaration. 
/*
class AnotherChild extends DemoClass{
* Compiler error like…
* Implicit super constructor DemoClass() is undefined for default constructor. 
* Must define an explicit constructor 
 
} */
public class ConstructorDemo {
           public static void main(String a[]) {
           // following code will not compile after removing comments 
          // because no suitable constructor found.
          // DemoClass dm1 = new DemoClass();
 
           // legal code
                    DemoClass dm2 = new DemoClass(“constructor found”);
          }
}
/*
 * Default constructor….
 * has same name and return type as class.
 * has no arguments.
 * includes no-arg call to super() constructor or call to this().
 * */
email

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.