Sunday, 30 June 2013

Using Interface and Polymorphism in Java Program



Using Interface and Polymorphism in Java Program

JAVA CODE:


//1.  Implements the runnable() interface
//Here interface is used by implementing the runnable at the class
public class threade implements Runnable
       {
        
       //2.  Implements the run() method of the runnable() interface to do the following:
//overriding through an Interface was used By implements the method run() with the runnable()

          
       public void run() {
              
       ////Note: The Thread.currentThread().getName() method is helpful for retrieving thread names.
              
       System.out.println(Thread.currentThread().getName()+ "running");
            
       //a.  Count down, starting with the number 5 and going to 0
       int i = 5;      
       while (i >= 0) {
                  
       ////b.  Print the name of the thread and the current value of countdown integer
                  
       //for each integer counted down
          //here polymorphism is used        
       System.out.println(Thread.currentThread().getName()+": "+i--);
               }
              
       //c.  Print "Blast Off!" when 0 is reached in the countdown
              
       System.out.println("Blast Off!");

           }  
       public static void main (String[] args)
         //Overriding - same method names with same arguments and same return types associated in a class and its subclass.
       //Overloading - same method name with different arguments, may or may not be same return type written in the same class itself.
       {
       //3.  Creates five threads in your main class giving each thread a name:
              
       //"Thread 1", "Thread 2", "Thread 3", "Thread 4", and "Thread 5"
          
       Thread thread1 = new Thread(new threade());
          
       thread1.setName("Thread 1");
          
       Thread thread2 = new Thread(new threade());
          
       thread2.setName("Thread 2");
          
       Thread thread3 = new Thread(new threade());
          
       thread3.setName("Thread 3");
          
       Thread thread4 = new Thread(new threade());
          
       thread4.setName("Thread 4");
          
       Thread thread5 = new Thread(new threade());
          
       thread5.setName("Thread 5");

          
       ////4.  Starts all five threads

          
       thread1.start();
          
       thread2.start();
          
       thread3.start();
          
       thread4.start();
          
       thread5.start();
         }
       }

Screenshots:

 

No comments:

Post a Comment