Saturday, February 27, 2016

What happens if a class doesn't implement all the methods defined in the interface?


A class must implement all methods of the interface, unless the class is declared as abstract. There are only two choices:
  • 1.Implement every method defined by the interface.
  • 2.Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects. 

The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e., non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The supclass may not implement the interface at all and just method signature is matched. For example,
interface MyInterface {  
  void m() throws NullPointerException;
} 

class SuperClass {
//NOTE : SuperClass class doesn't implements MyInterface interface 
  public void m() {
    System.out.println("Inside SuperClass m()");
  }
}

class SubClass extends SuperClass implements MyInterface {
}

public class Program {  
  public static void main(String args[]) {
    SubClass s = new SubClass();
    s.m();
  }
}


SimpleDateFormat and DateFormat

SimpleDateFormat is a class used to format and parsing dates in a locale sensitive manner. It is used to format date into text and parse text into date.
SimpleDateFormat is extends DateFormat class which is an abstract class for date/time formatting subclasses and provides many class methods for obtaining date/time matters based on any given locale. package com.lea.oops;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        Date date = new Date();
       
        String str = date.toString();
        System.out.println(str);
       
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
        System.out.println(dateFormat.format(date));
    }

}

Abstraction in Java

What is abstraction? Abstraction is the concept of segregate the implementation of interface. It will focus only on essential details instead of showing the full implementation details. Abstraction can be applied through abstract class and interface.
Abstract class is something which is incomplete and provide common information for the subclasses. You cannot create instance for abstract class. If you want to use it you need to make it complete or concrete by extending it.
When do you use abstraction? When you know something needs to be there but not sure how exactly it should like.
Abstraction key points
  • Use abstraction if you know something needs to be in class but implementation of that varies. 
  • You cannot create instance of abstract class using new operator. 
  •  Abstract class can have constructor 
  •  A class automatically become abstract class when any of its method declared as abstract. 
  •  Abstract method does not have method body 
  •  Variable cannot be made abstract. Its only for class and methods 
  •  If a class extends an abstract class or interface it has to provide implementation to all its abstract method to be concrete class.

Friday, February 26, 2016

Why abstract class can have constructor in Java?

The main reason is, when any class extend abstract class, constructor of sub class will invoke constructor of super class either implicitly or explicitly.

Write a program to find the first non repeated character in a String?

package com.lea.oops;

import java.util.HashMap;
import java.util.Scanner;

public class FirstNonRepeatedCharacter {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
       
        char c = firstNonRepeatedCharacter(s);
       
        System.out.println(c);
       
    }

    public static Character firstNonRepeatedCharacter(String str){
       
        HashMap<Character, Integer> hashMap = new HashMap<Character, Integer>();
       
        int i, length;
        Character c;
       
        length = str.length();
       
        for (int j = 0; j < length; j++) {
            c = str.charAt(j);
           
            if (hashMap.containsKey(c)) {
                hashMap.put(c, hashMap.get(c)+1);
            }else{
                hashMap.put(c, 1);
            }
        }
       
        for (int j = 0; j < length; j++) {
            c = str.charAt(j);
            if (hashMap.get(c) == 1) {
                return c;
            }
        }
       
        return null;
    }
}

Wednesday, February 24, 2016

Java Timer and TimerTask Tutorials

java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.

Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization. Timer class uses java.util.TaskQueue to add tasks at given regular interval and at any time there can be only one thread running the TimerTask, for example if you are creating a Timer to run every 10 seconds but single thread execution takes 20 seconds, then Timer object will keep adding tasks to the queue and as soon as one thread is finished, it will notify the queue and another thread will start executing.

Timer class uses Object wait and notify methods to schedule the tasks. TimerTask is an abstract class and we inherit it to provide concrete implementation. TimerTask class implements Runnable interface so it is a thread and hence your implementation of TimerTask is also a thread.

Example to print a repeated task for 5 times.
package com.lea.oops;

import java.util.Timer;
import java.util.TimerTask;

public class TimerTaskExample {

    Timer timer;
   
    public TimerTaskExample() {
        timer = new Timer();
        timer.schedule(new MyReminder(),  0, 1 * 1000);
    }
   
    class MyReminder extends TimerTask{
        int loop = 5;
      
        @Override
        public void run() {
            if (loop > 0) {
                System.out.println("Message "+loop+ "..!\n");
                loop--;
            } else {
                System.out.println("\nThat's it.. Done..!");
                timer.cancel();
            }
           }
      
    }
   
    /**
     * @param args
     */
    public static void main(String[] args) {
        new TimerTaskExample();
        System.out.println("Task scheduled..");
    }

}

Friday, February 19, 2016

How to use static fields within Spring XML Configuration

When configuring Spring through XML, you can use static fields in a similar way you use instances defined in the same XML or elsewhere. This is possible by using the util namespace as highlighted below.

<?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util-3.1.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">

  <bean id="myObject" class="com.javacreed.examples.howto.spring.StaticInXml">
    <constructor-arg>
      <list>
        <util:constant static-field="com.javacreed.examples.howto.spring.MyFields.OBJECT_1" />
      </list>
    </constructor-arg>
  </bean>

</beans>