Declarations and Access Control

Objective 1.2
Identify the legal return types for any method given the declarations of all related methods in this or parent classes.

Topics

What is a constructor? What is a default constructor?
Rules on constructors Return types of methods
Methods in the same class Methods in the sub class
Cram Sheet Quiz

What is a constructor?

A constructor is a special type of method that has the same name as the class name but has no return type. It is used in the creation of an object that is an instance of a class.

Constructors provide a way to initialize a new object.

 
class Calculator {
   int i, j;
   Calculator(int a, int b) {//constructor with two arguments
      i = a;
      j = b;
   }
   Calculator() {//default constructor
      i = 0;
      j = 0;
   }
   public static void main(String[] args) {
       Calculator c1 = new Calculator(); //default constructor called.
       Calculator c2 = new Calculator(5,6); 
}

Return to top


What is a default constructor?

A default constructor is a constructor without formal parameters or arguments.

 
class Hello{
    Hello(){ //default constructor
       System.out.println("Hello World");
   }
   public static void main(String args[]){
      Hello h = new Hello();//print "Hello World" on the screen
   }      
}

If a class contains no constructor declarations, then a default constructor is automatically provided.

 
class Hello{
    void say(){ 
       System.out.println("Hello World");
   }
   public static void main(String[] args){
      Hello h = new Hello(); //default constructor is provided by the compiler.
      h.say();  //print "Hello World" on the screen
   }      
}

If you provide any constructor for your class, you are responsible for creating a default constructor, otherwise a compile time error occurs.

 
class Base{
    Base(int i){
       System.out.println("single constructor");
    }
}

public class Test {
    public static void main(String args[]){
        Base b = new Base();//cannot compile, default constructor is missing.
    }
}

A compile-time error occurs if a default constructor is provided by the compiler but the superclass does not have an accessible constructor that takes no arguments

 
class SayHello {
    SayHello(String s) {
        System.out.println("Hello " + s);
    }
}
class SayIt extends SayHello{
   SayIt(String s) {
       super(s);
   }
   SayIt() {}
   public static void main(String[] args){
      SayIt sayit = new SayIt(); //error, no default constructor in superclass.
      
   }      
}

If the class is declared public, protected, private, or no access modifier then the default constructor is implicitly given the access modifier the class has. For example:

 
public class Point {
    int x, y;
}

is equivalent to the declaration:

public class Point {
    int x, y;
    public Point() { super(); }//added by the compiler
}

where the default constructor is public because class Point is a public class.

The rule that the default constructor of a class has the same access modifier as the class itself is simple and intuitive. Note, however, that this does not imply that the constructor is accessible whenever the class is accessible. Consider (code provided by SUN)

 
package p1;
public class Outer {
     protected class Inner{}
}
package p2;
class SonOfOuter extends p1.Outer {
    void foo() {
         new Inner(); // compile-time access error
    }
}

The constructor for Inner is protected. However, the constructor is protected relative to Inner, while Inner is protected relative to Outer. So, Inner is accessible in SonOfOuter, since it is a subclass of Outer. Inner's constructor is not accessible in SonOfOuter, because the class SonOfOuter is not a subclass of Inner! Hence, even though Inner is accessible, its default constructor is not.

Return to top


Rules on constructors

  1. The throws clause for a constructor is identical in structure and behavior to the throws clause for a method.
  2. If you do not specifically define any constructors in your class, the compiler will create a default constructor for your class.
  3. If you create constructors on your own, you will be responsible for the default constructor. The compiler will not create the default constructor for you.
  4. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented.
  5. All constructors call the default constructor of its parent class.
  6. When use super() to call super constructor, super() should be placed first before any statement in a constructor.
  7. If you call a super constructor by using super(paraList), such super constructor should exist.
  8. To call a constructor in its own class, use this().
  9. When use this(paraList) to call other constructor, this() should be placed first before any statement in a constructor.
  10. Constructors can be public, protected, default or private.
  11. Constructors cannot be native, abstract, static, strictfp,synchronized or final.
  12. Constructors can be overloaded, so that a class can have any number of constructors.

Return to top


Return types of methods

The signature of a method consists of :

The return type of a method is not considered as a method signature.

A method may return a value. For example, the method return an int type.

 
public int counter() {
    return count++;
}

If the method has no return value, use void keyword.

 
public void sayHello() {
    System.out.println("Hello");
}

A method can return any type, primitives or references.

 
public String sayHello() {
    return "Hello";
}

A method can return null, or return nothing.

 
public String sayHello() {
    ....   
    return null;
}
or 
public void sayHello() {
    ....
    return; //return nothing.
}

The return type has type promotion feature. For primitives, the small bit type may be promoted to bigger bit type

 
double adder(){
     int a = 5, b = 10;
     return a + b; //the result will be promoted to double.
}

For reference types, the return type must be compatible.

 
class A {}
class B extends A{}
...
   A method() {
     ...
     return new B();
   }
...
  Object amethod() {
     return new String();
  }
...

If a method return a value, you don't store such value when you call it, there is no error generated.

 
class Test {
    double adder(){
        int a = 5, b = 10;
        return a + b; 
    }
    public static void main(String[] args) {
       new Test().adder(); //OK
    }
}

Return to top


Methods in the same class

A class can have any number of methods. Every method should be unique in a class. The return data type does not contribute towards distinguishing between one method and another, even one of them is abstract method.

 
abstract class Point implements Move {
    int x, y;
    abstract void move(int dx, int dy); //compile time error
    void move(int dx, int dy) { x += dx; y += dy; }
}

If several methods have the same name and different parameters or order, such feature is called method overloading. The return types will not be considered as a difference.

 
class Test {
    void amethod(int i){} //compile time error 
    int amethod(int i) {} 
}

Return to top


Methods in the sub class

If you have a method with the same signature and return type as the method in the super class, such feature is called method overriding. Note that the return type is considered to tell if the method is overriding. Otherwise, a compile time error will occur.

 
class Super {
    String sayIt() {}
}
class Sub extends Super {
    String sayIt() {}//overriding method
}

If you have a method with the same name as the method in the super class but have different parameters or order, such feature is called runtime method overloading. The return type is not considered in such case.

 
class Super {
    String sayIt() {}
}
class Sub extends Super {
    String sayIt(String s) {}//runtime overloading
}

Recap:

Return to top


Cram sheet

  1. A constructor is a special method with the same name as its class identifier but doesn't return anything.
  2. A default constructor is a constructor without formal parameters or arguments.
  3. If a class contains no constructor declarations, then a default constructor is automatically provided.
  4. If you provide any constructor for your class, you are responsible for creating a default constructor, otherwise a compile time error occurs.
  5. If the class is declared public, protected, private, or no access modifier then the default constructor is implicitly given the access modifier the class has.
  6. A constructor is not inherited, so there is no need to declare it final and an abstract constructor could never be implemented.
  7. When use super() to call super constructor, super() should be placed first before any statement in a constructor.
  8. If you call a super constructor by using super(paraList), such super constructor should exist.
  9. To call a constructor in its own class, use this().
  10. When use this(paraList) to call other constructor, this() should be placed first before any statement in a constructor.
  11. Constructors can be overloaded, so that a class can have any number of constructors.
  12. Constructors cannot be native, abstract, static, strictfp,synchronized or final.
  13. Return value from a method may be promoted to the declared return type.
  14. If you don't store a return value from a method, there will be no error in your code.
  15. If a method returns a reference type, such method may return a null value

Return to top


Quiz

  1. Can the following code be compiled?

     
    class Base{
        Base(int i){
           System.out.println("single constructor");
        }
        Base() {}
        void Base() {}//treated as a method
        public static void main(String[] args) {
            Base b = new Base(); 
        }
    }
    

    Answer: YES. The default constructor has been provided.

  2. Can the following code be compiled?

     
    class Base{
        Base(int i){
           System.out.println("single constructor");
        }
    }
    class Sub extends Base {
        public static void main(String[] args) {
            Sub b = new Sub(); 
        }
    }
    

    Answer: No. The default constructor in a super class Base is missing.

  3. Which of the following statements are true?

     
    A. The default constructor has a return type of void
    B. The default constructor takes a parameter of void
    C. The default constructor takes no parameters
    D. The default constructor is not created if the class has any constructors of its own.
    

    Answer: B, D.

  4. What is the difference between overloading and overriding methods?
  5. What is the runtime overloading?
  6. What is the method signature?
  7. In which situation, a method can return null?
  8. Given the following class definition

     
    1. public class Test{
    2.     public void amethod(int i){}
    3.         //Here
    4. }
    
    Which of the following would be legal to place on line 3 individually ?
    A. public int amethod(int z){} 
    B. public int amethod(int i,int j){return 99;} 
    C. protected void amethod(long l){ } 
    D. private void amethod(){}
    E. void Amethod(int i) {}
    

    Answer: Overloading issue. B, C), D, E. Note E has a different method name.

  9. Given the following class definition

     
    class Base{
        public void amethod(){
            System.out.println("Base");
       }
    }
    public class Sub extends Base{
        public static void main(String[] args){
            Sub s = new Sub();
            s.amethod();
        }
    }
    
    Which of the following methods in class Sub would compile and cause the 
    program to print out the string "Hello"?
    
    A. public int amethod(){ System.out.println("Hello");}
    B. public void amethod(long l){ System.out.println("Hello");}
    C. public void amethod(){ System.out.println("Hello");}
    D. public void amethod(void){ System.out.println("Hello");} 
    

    Answer: Overriding issue. Only C has exact return type and signature.

Return to top