Skip to main content

Methods and Constructors


Introduction:
Welcome, this tutorial will teach you about Constructors and Methods in Java.

What is a 'Method'?
A method is a block of script which performs for a purpose. The use of methods is to avoid re-writing the same scripts over and over again because instead, you are able to use the same method every time you need to run that particular script. Methods normally return a value once ran but can run without returning anything. Methods can be custom created by the programmer or they can be built in to Java... for example; the Get function to retrieve a value from an index within an Array.

What is a 'Constructor'?
Constructors are very similar to methods but each class can only have one. The constructor must be the name of the class and has no type so it can not return any values. The constructor is the first thing that is ran once a new class is called.

Method Example:
Here is a custom method I have created which is ran from the Constructor when the class is ran from the main void which is the first method ran once a Java Application opens...

  1. public class Main {
  2. public static void main(String args[]) {
  3. new Main();
  4. }
  5. public Main() {
  6. customMethod();
  7. }
  8. private static void customMethod(){
  9. System.out.println("Testing output.");
  10. }
  11. }

Finished!

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.