Posts

Showing posts from October, 2014

Encapsulation in Java

Consider a case that can help you better understand the concept of encapsulation. Assume there is a class Student with 'id' and 'name' attributes. We want to enforce, the student id must be greater than 0. Assume another class StudentTest that creates a Student object, initilize its attributes and print the initilalized values. See the code sample here: public class Student { int id; String name; } public class StudentTest { public static void main(String[] args) { Student student = new Student(); // object instantiation // Initialize instance attributes student.id = -100; student.name = "Alice23"; // Lets just print the instance attribute values System.out.println("ID : " + student.id); System.out.println("Name : " + student.name); } } You see, we set the id to -100 and name to Alice23. Both attributes values are incorrect. But if we compile the code and run

Access Modifiers in Java

When we define attributes or methods in a class, we can access those attributes and methods by creating that class object. If the method is static, it can be accessed using class name. For example if there is a class named Student, we can create its object and access its methods, lets see the code sample. public class Student { int id; String name; void registerCourse(String courseCode){ System.out.print("registerCourse called with code: " + courseCode); } } public class StudentTest { public static void main(String[] args) { Student student = new Student(); student.id = 1; student.name = "Alice"; System.out.println("ID : " + student.id); System.out.println("Name : " + student.name); student.registerCourse("CSC245"); } } In StudentTest class, we have created the Student object and accessed id and name attribute using the object name. We named the ob

How to Redirect in Spring MVC

We often need to redirect our request to another controller. Its very easy to do in Spring MVC. In below code sample, I have created a controller method i.e. list which is mapper to context/users/ URL. It just displays the list of users. There is another method i.e. save, it process the POST request and used to save data to database. I have not actually saved the data into DB because that is not our object in this post. We want to see, when save controller is called, and we have done with saving data into DB, how we can redirect our request to /users/ controller from /save/ controller method. Its very simple, below I share the code sample I have created to demonstrate the Spring MVC redirect: package com.springpoc.controllers; import com.springpoc.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.spring