Showing posts with label main method. Show all posts
Showing posts with label main method. Show all posts

Friday, 21 February 2014

Abstract Methods and Abstract Classes

Abstract Method
An abstract method is a method that is declared without an implementation. An abstract method is declared using the keyword abstract.

Syntax
abstract returnType methodName(parameters)

Example
abstract int sum(int operand1, int operand2);

Abstract Class
An abstract class is declared using the keyword abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Syntax
    abstract class ClassName{
        /* may or may not contain abstract methods */
    }

If a class extends the abstract class, then it must provide the implementation for all the abstract methods in the abstract class, otherwise the class should be declared as abstract.

The main purpose of abstract class is to use the common code in the sub classes.

Example
abstract class Animal{
 String name;

 String getName(){
  return name;
 }

 void setName(String name){
  this.name = name;
 }

 abstract String run();
}

class Elephant extends Animal{
 String run(){
  return "I can run at the speed of 25 mph";
 }
}
   
class Lion extends Animal{
 String run(){
  return " I can run at the speed of 50 mph";
 }
}
     
class Tiger extends Animal{
 String run(){
  return "I can run at the speed of 60 mph";
 }
}
     
class AbstractTest{
 public static void main(String args[]){
  Animal anim1 = new Elephant();
  anim1.setName("Gaja");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Lion();
  anim1.setName("Aslam");
  System.out.println(anim1.getName() +":" + anim1.run());

  anim1 = new Tiger();
  anim1.setName("PTR");
  System.out.println(anim1.getName() +":" + anim1.run());
 }
}


Output
Gaja:I can run at the speed of 25 mph
Aslam: I can run at the speed of 50 mph
PTR:I can run at the speed of 60 mph

Every Animal has a name, so getName() and setName() are common to all the animals, So the implementation for these methods kept in the abstract class Animal. Where as different Animals runs at different speeds, so the run() method declared as abstract, so all the concrete classes that are extending the class Animal, must provide the implementation for the run method.

Some Points to Remember
1. Can I create constructor inside the abstract class ?
Yes, but you can't initialize an object for the abstract class.

Example
abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 
2. Can I make abstract class as final ?
No, If you make abstract class as final, then no other class can able to extend it. So, compiler throws error. Abstract and final can't be used together.

Example
final abstract class Animal{
 String name; 

 Animal(String name){
  this.name = name;
 }
}
 

When you tries to compile the above program, compiler throws the below error.
 Animal.java:1: error: illegal combination of modifiers: abstract and final
    final abstract class Animal{
    ^
    1 error


3. Can I make abstract method as final ?
No, If you make abstract method as final, then no other class can able to override it. So, compiler throws error. Abstract and final can't be used together.

Example
abstract class Animal{
 String name; 

 final abstract void run();

 }
}

When you tries to compile the above program, compiler throws the below error.
Animal.java:4: error: illegal combination of modifiers: abstract and final
final abstract void run();
^
1 error
 

4. Can I define main method in abstract class ?
Yes, it is valid, but creation of object to the abstract is not possible.

Example
abstract class Animal{
 String name; 

 public static void main(String args[]){
  System.out.println("I am in main method");
 }
}
   
Output
I am in main method

5. What is wrong with the below program ?
    abstract class Animal{
        void run();
    }

Above program won't compile, since if you want to make a method as abstract, then it must be declared with the specifier abstract. When you tries to compile, compiler throws the below error.

Animal.java:2: error: missing method body, or declare abstract
void run();
^
1 error

To make the program run you have two options.

Option 1
    Make the method as abstract.

    abstract class Animal{
        abstract void run();
    }

Option 2
provide the implementation for the method run().

    abstract class Animal{
        void run(){
        }
    }
  
6. An abstract class allowed to have static methods, where as interfaces have instance methods only (From Java8 onwards, we can add static methods to interfaces).

7. The methods declared in interface are abstract by default.

8. Can an interface has constructor ?
No

9. Can an abstract class have a final method?
Yes, it can. But the final method cannot be abstract itself

Example
    abstract class Animal{
        final void print(){
            System.out.println(" I am final method in abstract class");
        }
    }


Final Classes and Methods                                                 Abstract Class vs Interface                                                 Home

Saturday, 15 February 2014

main method

In Java, every application must contain a main method. Program execution starts from main method.

Main method signature in Java is
    public static void main(String[] args)

public: main method should be called by JVM, which is not part of the project, so to make it available for the JVM, main method declared as public.

static: Before the main method is called, no objects are created. Having the static keyword means, the method can be called without creating any objects first.

void: In Programming languages, return codes tells the status of particular program/process/function execution. Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

Java supports multi threading, so the main thread may finishes first, before other threads completes execution, So what status code the main thread returns, even it don't know about the executions of other threads started in main method. So in Java there is void return type for main method.

String args[]: Used to pass the command line arguments. Since you can convert the String values to any compatible type of primitive values like int, float, double etc.,

Some Points to Remember

1. Is overloading of main method valid ?
   Yes
class MainEx{
  public static void main(int a){
    System.out.println("in Integer " +a);
  }

  public static void main(double a){
    System.out.println("in double " +a);
  }

  public static void main(char a){
    System.out.println("in char " +a);
  }

  public static void main(String args[]){
    main(10);
    main(10.11);
    main('a');
  }
}
            
Output
in Integer 10
in double 10.11
in char a
            
2. You can call main method in any way like
     public static void main(String args[])
               (OR)
     static public void main(String args[])

3. Why is the Java main method static?
Before the main method is called, no objects are created. Having the static keyword means the method can be called without creating any objects first.

4. Why main method is public static in Java ?
main method should be called by JVM, which is not part of the project, so to make it available for the JVM, main method declaed as public.

Before the main method is called, no objects are created. Having the static keyword means the method can be called without creating any objects first.

5. Why main() in java void ?
In Programming languages, return codes tells the status of particular program/process/function execution. Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

Java supports multi threading, so the main thread may finishes first, before other threads completes execution, So what status code the main thread returns, even it don't know about the executions of other threads started in main method. So in Java there is void return type for main method.


6. Is the below program run?
    class MainEx{
        public static void main(){
        }
    }

Above program compiles fine, but Runtime, JVM tries to find the main method with signature
    public static void main(String args[])
there is no main method with the above signature in the program, so below run time error thrown

Error: Main method not found in class MainEx, please define the main method as:

    public static void main(String[] args)



Garbage Collection                                                 Command line Arguments                                                 Home

Friday, 31 January 2014

Running Simple Hello World Applcation in Java

                                       Installation and setting up java

Installation :

   You can download the java software from the below location

      http://www.oracle.com/technetwork/java/javase/downloads/index.html


1. Install the product.

2. Setting up the java environment

2.a On Windows

   Suppose you install the java in the below directory,

       C:\Program Files\Java

   Then java compiler (javac) and java launcher (java) will present in

        C:\Program Files\Java\jdk1.7.0_13\bin

  We need to add the “C:\Program Files\Java\jdk1.7.0_13\bin” to system path, then we can run our java programs from any where

Follow the below steps

Step1 : Right click computer icon, and open the properties window.

Step 2:Click on the Advanced system settings tab as shown below. Then it will open the system properties window.



Step3: Open the System properties and choose the Advanced tab. Click on the “Environment Variable” button.


Step 4
You will get a window like below. It contains 2 sections, one for user variables and other for System variables section.


Edit the path from system variables section

Append the java bin path to the value filed of System variable "path".

Before appending prepend a semicolon like below

;C:\Program Files\Java\jdk1.7.0_13\bin


 
Press Ok.

How to check whether you set the path properly or not

Open command prompt and type javac. If you see the output like below. You successfully set up the java environment.


On Open Systems

If you install the java on below directory “/usr/java7”

Then java compiler (javac) and java launcher (java) present in the directory “/usr/java7/bin”

You have to update the path like below

      export PATH=/usr/java7/bin/:$PATH

              OR

     you update the path variable in /etc/environment file for linux or .profile file in AIX like below

       export PATH=/usr/java7/bin/:$PATH


Hello World Application
 
 Lets start by simple program usually printing "Hello World".

Open notepad, and type the below code

class Hello{
    public static void main(String args[]){       
        System.out.println("Hello World");
    }
}
Save the file as Hello.java

Let the file saved in location "C:\java Programs". Open command prompt and goto the directory where the file is saved.




How to compile the Program

   Use the below command

      javac Hello.java

How to run the Program

   Use the below Command

      java Hello

After you run the program with the command "java Hello" You will see the output "Hello World" on the console

Discussion:

1. File name should be exactly equal with your class Name. Here class name is "Hello", so i saved the file name as Hello.java.

Close Look at the Hello World program

--------------------------------------

Hello World Program has mainly 3 Components.

1. Class Definition

2. The Main Method

3. println method


1. Class Definition

class Hello{
   public static void main(String args[]){
        System.out.println("Hello World");
   }
}

Java is Object Oriented language. So Everything you write must be enclosed in the class declaration.

Basic Syntax of class is

class Class_Name{

//Statements

}
By convention, a class Name always starts with Capital letter followed by small letters like Abc, Hello, and each subsequent word in the class declaration also starts with capital letter like "ThreadExample"

2. The Main Method
class Hello{
    public static void main(String args[]){
      System.out.println("Hello World");
   }
}

In the Java programming language, every application must contain a main method whose signature is:


Don't bother about the signature of the main method, you will learn later. Now remember, Program execution always starts from main method.

3. println method
it simply prints the information whatever you given to it, to the terminal or console.




Features Removed from C and C++                                                 Data Types in Java                                                 Home