Monday, 31 August 2015

Method Overriding

Method overriding

It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.

It is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super classes or parent classes.

The implementation in the subclass overrides (replaces) the implementation in the super-class by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class.

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the super-class overrides the super-class's method.


Overriding is a feature that is available while using Inheritance.


This way the new method masks the parent method and would get invoked by default.

class Thought {
       public void message() {
              System.out.println("I feel like I am diagonally parked in a parallel universe.");
       }
}

public class Advice extends Thought {
       @Override  // @Override annotation in Java 5 is optional but helpful.
       public void message() {
              System.out.println("Warning: Dates in calendar are closer than they appear.");
       }
}

Return type in method Overriding

Before Java 5.0, when you override a method, both parameters and return type must match exactly.

In Java 5.0, it introduces a new facility called covariant return type, override a method with the same signature but returns a subclass of the object returned.
A method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the super-class.

After JDK 1.5, java supports covariant returns, that is, the specialization of the return type to a subtype.
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:
· If R1 is void then R2 is void.
· If R1 is a primitive type, then R2 is identical to R1.
· If R1 is a reference type then:
· R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion, or

· R1 = |R2|

Rotate 2-D matrix by 90

Given N*M matrix, rotate it by 90 degree right

package core.geeks;
class Rotate90Degree {
      
       private static void rotateMatrix(int[][] array) {
              int oRow = array.length;
              int oCol = array[0].length;
              int[][] tArr = new int[oCol][oRow];

              int tCol = 3;
              for (int i = 0; i < oRow; i++){
                     for(int j = 0;  j < oCol; j++){
                           tArr[j][tCol] = array[i][j];
                     }
                     tCol--;
              }

              printGrid(tArr);
       }
      
       public static void main(String args[] ) throws Exception {
              int[][] array = {  {0, 1, 2, 3, 4},
                           {5, 6, 7, 8, 9},
                           {10, 11, 12, 13, 14},
                           {15, 16, 17, 18, 19}};
              rotateMatrix(array);
       }

       public static void printGrid(int[][] a) {
              for(int i = 0; i < a.length; i++) {
                     for(int j = 0; j < a[i].length; j++) {
                           System.out.printf("%5d ", a[i][j]);
                     }
                     System.out.println();
              }
       }
}

Output:
   15    10     5     0
   16    11     6     1
   17    12     7     2
   18    13     8     3
   19    14     9     4


Friday, 28 August 2015

Spring REST JSON response

Spring REST JSON response

Spring’s @ResponseBody annotation and returning the object that we want to send to the client.

The @ResponseBody annotation tells Spring that we will be returning data in the response body rather than rendering a JSP.

When the @ResponseBody annotation is used, Spring will return the data in a format that is acceptable to the client.

JSON response:
If the client request has a header to accept JSON and Jackson-Mapper is present in the classpath, then Spring will try to serialize the return value to JSON.

XML response:
If the request header indicates XML as acceptable (accept= application/xml) and Java Architecture for XML Binding (JAXB) is in the classpath and the return type is annotated with JAXB annotation, Spring will try to marshall the return value to XML.

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import com.abusecore.controller.RestController;
import com.abusecore.model.Count;
import com.abusecore.services.IDataServices;

@Controller
@RequestMapping("/AbuseCore-1")
public class RestController {

       @Autowired
       IDataServices dataServices;
      
      
       /** Logger class to display logs. */
       static final Logger logger = Logger.getLogger(RestController.class);

      
       @RequestMapping(value="/count-tickets.json",method=RequestMethod.GET)
       public @ResponseBody Count getTicketsCount() {
              Count count = dataServices.getTicketsCount();
              logger.info("total tickets :" + count);
              return count;
       }
}

Singleton beans scopes in Spring

Beans with different Id’s have Singleton instance


singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container.


NO, Similar beans with different ids make the different instance (Even scope is defined as Singleton); because the singleton scope checked on the basis of bean ids.

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd"

       default-autowire="byName" default-autowire-candidates="*">

       <context:annotation-config />

       <bean id="id1" class="spring.core.singleton.Singleton">
              <property name="name" value="Rajesh kumar"></property>
       </bean>

       <bean id="id2" class="spring.core.singleton.Singleton">
              <property name="name" value="Awadh kumar"></property>
       </bean>
</beans>

package spring.core.singleton;
public class Singleton {
      
       private String name;

       public String getName() {
              return name;
       }

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

package spring.core.singleton;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSingletonScope {
       public static void main(String[] args) {

              ApplicationContext appContext = new ClassPathXmlApplicationContext
                           ("spring/core/singleton/autowiring-spring.xml");
             
              Singleton singleton1 = appContext.getBean("id1", Singleton.class);
             
              Singleton singleton2 = appContext.getBean("id2", Singleton.class);
             
             
              System.out.println(singleton1.getName());
              System.out.println(singleton2.getName());

              if(singleton1==singleton2) {
                     System.out.println("singleton");
              } else {
                     System.out.println("not singleton");
              }
       }
}

Output:
Rajesh kumar
Awadh kumar
not singleton
Related Posts Plugin for WordPress, Blogger...