Which class is super class of every class

Does constructor return any value

Answer : Below are point why it doesn’t return any value:

  • If you call a constructor the return value would be new object
  • It will be already created before you do something inside code.
  • If you provide return statement inside constructor it will be treated as method

Please see example below:

package com.javahonk.constructorchain;

public class Toyota {

	//Be Careful : On below code java allowed this 
	//once you provide return statement java will be treated as method
	//but don't get confused. Java will treat as method
	//will give you warning - This method has a constructor name
	public int Toyota() {
		return 10;
	}

	//For information : Only public, protected & 
	//private are permitted for constructor
	private Toyota(){
		System.out.println("I am actual constructor");
	}

	public static void main(String args[]) {
		Toyota toyota =new Toyota();
		int i =toyota.Toyota();
		System.out.println("Retrun value from same constructor"
				+ " name as method name: "+i);

	}

}

 

Output:


Does constructor return any value

 

Leave a Reply

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