Java Constructor Inheritance

Whenever any class is inherited in Java using extends keyword, the subclass calls the default constructor of its parent class, see below example of inheritance in default constructor classes:


package com.evaluatethecode;

public class DefaultConstructorInheritance {

public static void main(String[] args) {
new C();
}
}

class A {

A() {
System.out.println("Level 1");
}
}

class B extends A{
B() {
System.out.println("Level 2");

}
}

class C extends B {
C() {
System.out.println("Level 3");
}
}

Output:
Level 1
Level 2
Level 3


Default constructor exists implicitly in all class until there is no parameterized constructor in that class, once the parameterized constructor is created that class does not have default constructor, if we want default constructor along with parameterized one, then we have to explicitly define default constructor in that case. See below example of inheritance in parameterized constructor classes:



package com.evaluatethecode;

public class ParameterizedConstructorInheritance {
public static void main(String[] args) {
new C1();
}
}

class A1 {

A1() {
System.out.println("Default constructor");
}
A1(String val) {
System.out.println("Level 1");
}
}

class B1 extends A1{

B1(String val) {
System.out.println("Level 2 "+val);

}
}

class C1 extends B1 {
C1() {
super("Initialize parent constructor with super() as it does not have
        default constructor");
System.out.println("Level 3");
}
}

Output:
Default constructor
Level 2 Initialize parent constructor with super() as it does not have 
default constructor
Level 3

Java Thread start and join method example

 When implementing Runnable interface for Thread then below points need to remember:

(1) Implement run() method

(2) run() method should be called with start() method, directly calling run() will not work as thread.

(3) If there is no join() call, then even after executing start(), first the calling method will complete its execution then it will go to run().

(4) If there is join() call after start() then code will directly go to run() and complete run() execution first then come back to calling method for further execution.

(5) join() should be called after start() and catching InterruptedException is mandatory for join().


package com.evaluatethecode;

public class ThreadWithoutJoinExample implements Runnable {

public static void main(String[] args) {

System.out.println("Calling start() is required to execute run()");
Thread etcThread = new Thread(new ThreadJoinExample());
etcThread.start();
System.out.println("This method does not have join method call ");

}

public void run() {
System.out.println("Run method: Evaluate the code");
}
}

Output:
Calling start() is required to execute run()
This method does not have join method call 
Run method: Evaluate the code

package com.evaluatethecode;

public class ThreadJoinExample implements Runnable{

public static void main(String[] args) {

Thread etcThread = new Thread(new ThreadJoinExample());
etcThread.start();
System.out.println("Before join method call");
try {
etcThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("After join method call");

}

public void run() {
System.out.println("Run method: Evaluate the code");
}
}

Output:
Before join method call
Run method: Evaluate the code
After join method call

Java Dateformat and Calender example

 Below example is to just understand the syntax of DateFormat and Calender in Java.


package com.evaluatethecode;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateExampleJava6 {

public static void main(String[] args) {

DateFormat etcDFJpn = DateFormat.getDateInstance(DateFormat.LONG,
Locale.JAPAN);
DateFormat etcDFUs = DateFormat.getDateInstance(DateFormat.LONG,
Locale.US);
DateFormat etcDFUk = DateFormat.getDateInstance(DateFormat.LONG,
Locale.UK);
DateFormat etcDFGrmn = DateFormat.getDateInstance(DateFormat.LONG,
Locale.GERMAN);

Date etcDate = new Date();

System.out.println(etcDFJpn.format(etcDate));
System.out.println(etcDFUs.format(etcDate));
System.out.println(etcDFUk.format(etcDate));
System.out.println(etcDFGrmn.format(etcDate));

Calendar etcCal = Calendar.getInstance();
etcCal.set(Calendar.YEAR, 2009);
etcCal.set(Calendar.MONTH, 0);
etcCal.set(Calendar.DAY_OF_MONTH, 1);

etcDFJpn.setCalendar(etcCal);

System.out.println(etcCal.getTime());
}



}


Output:

2023/01/05
January 5, 2023
05 January 2023
5. Januar 2023
Thu Jan 01 01:36:20 IST 2009


Java - Different types of method overriding example


In this example I had created 3 level of Inheritance, Class A as grandparent, Class B as parent and Class C as child.
All these classes have methods and I had mentioned in comments what kind of overriding is possible and what gives error.

Example:

Grand Parent class A:

package blogspot.evaluatethecode.overriding;

import java.io.FileNotFoundException;
import java.io.IOException;

public class A {

   
public void test() {
      System.
out.println("Super class A");
   }
 
   
public int test(int a) {
      System.
out.println("Super class A int test(int)");
      
return a;
   }
 
   
public Double test(int a,int b) {
      System.
out.println("Super class A Double test(int,int)");
      
return (double) (a/b);
   }
 
   
public Number test(double a) {
      
return a;
   }
 
   
public String test(String a) {
      
return a;
   }
 
   
public Object test(String a, String b) {
      
return a+" "+b;
   }
 
   
public void test(char a) throws Exception{
      System.
out.println("Exception test(char)");
   }
 
   
public void retest(char a) {
      System.
out.println("Super class without Exception test(char)");
   }
 
   
public void testFile() throws FileNotFoundException {
      System.
out.println("Super class file not found exception");
   }
 
   
public void testIO() throws IOException {
      System.
out.println("Super class IO exception");
   }
 
   
public void testIO2() throws IOException {
      System.
out.println("Super class IO2 exception");
   }
 
   
public void testIO3() throws IOException {
      System.
out.println("Super class Checked exception");
   }
 
   
public void testIO4() throws NullPointerException {
      System.
out.println("Super class throws non checked exception");
   }
 
   
protected void protectedTest() {
      System.
out.println("Super class protected");
   }
 
   
public void publicTest() {
      System.
out.println("Super class public");
   }
 
   
private void privateTest() {
      System.
out.println("Super class private");
   }
 
}



Parent class B:

package blogspot.evaluatethecode.overriding;

import java.io.FileNotFoundException;
import java.io.IOException;

public class extends A {

   
public void test() {
      System.
out.println("Sub class B");
   }
 
   
/*public Integer test(int a) {
      System.out.println("Super class A int test(int)");
      return a;
   }*/
   // This gives compilation error as return type incompatible with super class
 
   /*public double test(int a,int b) {
      System.out.println("Super class A Double test(int,int)");
      return (double) (a/b);
   }*/
   // This also gives compilation error as return type incompatible with Super class
 
   /*public double test(double a) {
      return 1.0;
   }*/
   // This also gives compilation error as return type incompatible with Super class
 
   
public Double test(double a) {
      
return 1.0;
   }
 
   
/*public Object test(String a) {
      return a;
   }*/
   // This also gives compilation error as return type incompatible with Super class
 
   
public String test(String a, String b) {
      
return b+" "+a;
   }
 
   
public void test(char a) {
      System.
out.println("Subclass without Exception test(char)");
   }
 
   
/*public void retest(char a) throws Exception{
      System.out.println("Sub class with Exception test(char)");
   }*/
   //Exception is not compatible with throws clause of Super class
 
   /*public void testFile() throws IOException {
      System.out.println("Super class file not found exception");
   }*/
   //Exception is not compatible with throws clause of Super class
 
   
public void testIO() throws FileNotFoundException {
      System.
out.println("Sub class File Not Found Exception");
   }
 
   
public void testIO2() {
      System.
out.println("Sub class IO2 without exception");
   }
 
   
public void testIO3() throws NullPointerException {
      System.
out.println("Sub class not checked exception");
   }
 
   
/*public void testIO4() throws IOException {
      System.out.println("Sub class throws checked exception");
   }*/
   //Exception is not compatible with throws clause of Super class
 
   
public void protectedTest() {
      System.
out.println("Super class protected sub class public");
   }
 
   
/*protected void publicTest() {
      System.out.println("Super class public");
   }*/
   // This gives compilation error - cannot reduce visibility of inherited method
 
   
private void privateTest() {
      System.
out.println("Super class private sub class private, it is not overrriden but both of them considered as separate method");
   }
 
   
public static void main(String[] args) {
      A a = 
new A(); // Runtime polymorphism/ Dynamic method dispatch
      
a.test();
    
      a= 
new B(); // Runtime polymorphism/ Dynamic method dispatch
      
a.test();
      System.
out.println(a.test(2.2));
      System.
out.println(a.test("Vikas""Thakur"));
      
/*System.out.println(a.test('a'));*/
      //This gives compilation error PrintStream is not applicable for the arguments (void)
    
      
try {
         a.test(
'a');
      } 
catch (Exception e) {
         e.printStackTrace();
      }
    
      
try {
         a.testIO();
         a.testIO2();
         a.testIO3();
      } 
catch (IOException e) {
         e.printStackTrace();
      }
      
//If we call this subclass method without try catch it gives compilation error
      
a.protectedTest();
    
      
/*a.privateTest();*/
      //This gives compilation error while calling - This method from super class is not visible
      
new B().privateTest();
    
   }
 
}


Child class C:

package blogspot.evaluatethecode.overriding;

public class extends B{

   
public void test() {
      System.
out.println("Third level hierarchy inheritance Sub class A method overriding");
   }
 
   
public static void main(String[] args) {
      A a = 
new C();
      a.test();
    
      A a2 = 
new A();
      a2.test();
   }
 
}


Output of Class B:

Super class A
Sub class B
1.0
Thakur Vikas
Subclass without Exception test(
char)
Sub
class File Not Found Exception
Sub
class IO2 without exception
Sub
class not checked exception
Super
class protected sub class public
Super class private sub class private, it is not overrriden but both of them considered as separate method


Output of Class C:

Third level hierarchy inheritance Sub class A method overriding
Super
class A







JSF-Primefaces database connectivity with Spring JdbcTemplate framework example


This example will explain how to connect database with JSF-Primefaces using Spring JdbcTemplate framework.




Step 1:
Create archetype web-app maven project in Eclipse IDE for Java EE and write all dependencies in pom.xml file.




pom.xml:


<project xmlns="http://maven.apache.org/POM/4.0.0"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.blogspot.evaluatethecode</groupId> <artifactId>JsfPrimefacesSpringJdbc</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>JsfPrimefacesSpringJdbc Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <mysql.connector.version>5.1.9</mysql.connector.version> <spring.version>4.3.0.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.2.9</version> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.2.9</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>el-impl</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>com.sun.el</groupId> <artifactId>el-ri</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>org.primefaces</groupId> <artifactId>primefaces</artifactId> <version>6.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.connector.version}</version> </dependency> </dependencies> <build> <finalName>JsfPrimefacesSpringJdbc</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.0</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>


Step 2:
Create JSF managed bean classes


package blogspot.evaluatethecode.bean;


import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

import blogspot.evaluatethecode.dao.IndexDao;
import blogspot.evaluatethecode.model.Users;

@Component
@ManagedBean(name = "indexBean")
@RequestScoped
@Scope("request")
public class IndexBean {
   
   private List<Users> userList;
   private String username;
   private String firstname;
   private String lastname;
   private String email;
   private String address;
   private String phone;
   
   
   public String getUsername() {
      return username;
   }
   public void setUsername(String username) {
      this.username = username;
   }
   public String getFirstname() {
      return firstname;
   }
   public void setFirstname(String firstname) {
      this.firstname = firstname;
   }
   public String getLastname() {
      return lastname;
   }
   public void setLastname(String lastname) {
      this.lastname = lastname;
   }
   public String getEmail() {
      return email;
   }
   public void setEmail(String email) {
      this.email = email;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   public String getPhone() {
      return phone;
   }
   public void setPhone(String phone) {
      this.phone = phone;
   }
   public List<Users> getUserList() {
      return userList;
   }
   public void setUserList(List<Users> userList) {
      this.userList = userList;
   }
   
   @Autowired
   private IndexDao indexDao;
   
   public void setIndexDao(IndexDao indexDao) {
      this.indexDao = indexDao;
   }
   
   @PostConstruct
       public void init() {
       
      this.setUserList(indexDao.getUsersList());
      
    }
   
   public void addUser(ActionEvent actionEvent) {
      System.out.println("Inside add user");
      Users users = new Users();
      users.setUsername(this.getUsername());
      users.setFirstname(this.getFirstname());
      users.setLastname(this.getLastname());
      users.setAddress(this.getAddress());
      users.setEmail(this.getEmail());
      users.setPhone(this.getPhone());
      
      indexDao.insertUser(users);
      this.setUserList(indexDao.getUsersList());
      
      System.out.println("Successfully added");
      resetAll();
   }
   
   private void resetAll() {
      this.username = null;
      this.firstname = null;
      this.lastname = null;
      this.address = null;
      this.email = null;
      this.phone = null;
      
   }
   
}





Step 3:
Create DAO classes for JDBC retrieve and save operations.

DAO Interface:

package blogspot.evaluatethecode.dao;

import java.util.List;

import blogspot.evaluatethecode.model.Users;

public interface IndexDao {

   public List<Users> getUsersList();
   public int insertUser(Users users);
   
}

DAO Class:

package blogspot.evaluatethecode.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import blogspot.evaluatethecode.model.Users;  

@Repository("indexDao")
public class IndexDaoImpl implements IndexDao{
   
   @Autowired   private JdbcTemplate jdbcTemplate;  
     
   public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
       this.jdbcTemplate = jdbcTemplate;  
   }

   public List<Users> getUsersList() {
      String sql = "select userid, username," +
            " firstname, lastname, email, address, phone from users";
      List<Users> usersList = jdbcTemplate.query(
            sql, new BeanPropertyRowMapper<Users>(Users.class));
      return usersList;
   }

   public int insertUser(Users users) {
      String sql = "insert into users(username, firstname," +
            " lastname, email, address, phone) values " +
            "(?, ?, ?, ?, ?, ?)";
      
      int value = jdbcTemplate.update(sql,
                new Object[] { users.getUsername(), users.getFirstname(), 
                  users.getLastname(), users.getEmail(), users.getAddress(), 
                  users.getPhone() });
      return value;
   }

   
}


Step 4:
Create database table in MYSQL database

create database evaluatethecode
use database evaluatethecode

create table users (userid int primary key AUTO_INCREMENT,
 username varchar(20), firstname varchar(20),lastname varchar(20),
 email varchar(20),address varchar(50),phone varchar(20));


Step 5:
Create configuration files – web.xml, faces-config.xml and, application-Context.xml

web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>JsfPrimefacesSpringJdbc Maven Webapp</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <welcome-file-list> <welcome-file>index.xhtml</welcome-file> </welcome-file-list> <servlet> <servlet-name>facesServlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>facesServlet</servlet-name> <url-pattern>/jsf/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>facesServlet</servlet-name> <url-pattern>*.xhtml</url-pattern> </servlet-mapping> </web-app>

faces-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
   version="2.1">
<application> <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver </el-resolver> </application> </faces-config>

application-Context.xml:

<?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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="blogspot.evaluatethecode" /> <context:annotation-config /> <bean id="driverManagerDataSource"
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
 
<property name="driverClassName" value="com.mysql.jdbc.Driver" />  
<property name="url" value="jdbc:mysql://localhost:3306/evaluatethecode" />  
<property name="username" value="root" />  
<property name="password" value="mysql" />  
</bean>  
  
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
<property name="dataSource" ref="driverManagerDataSource"></property>  
</bean>  

<bean id="indexDao" class="blogspot.evaluatethecode.dao.IndexDaoImpl">  
<property name="jdbcTemplate" ref="jdbcTemplate"></property>  
</bean>  

</beans>




Step 6:
Build maven project and deploy the war file inside target folder to Glassfish server.
Command to build maven project -> mvn clean install
Click here for deployment steps


Output: