Friday, 5 April 2013

Customize Examples of OOPS & Exceptions in Java


   The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. 
Using private constructor we can ensure that no more than one object can be created at a time. 

By providing a private constructor you prevent class instances from being created in any place other than this very class.
So, Using private constructor and factory method, we can create singleton class.

class Mysingleton {

private static Mysingleton instance;


private Mysingleton () {}


public static Mysingleton getInstance() {

if (instance == null) {

instance = new Mysingleton ();

}

return instance;

}


@Override

protected Object clone() {

return this;

}


public static void main(String[] args) {

Mysingleton t1 = Mysingleton.getInstance();

Mysingleton t2 = Mysingleton.getInstance();

System.out.println(t1);

System.out.println(t2);

}

}

=====================================================
  //Singleton .java
   
 import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;


public class Singleton {

private static Singleton instance;

private static final String URL = "jdbc:sqlserver://DESKTOP-MITTPRS\\SQLEXPRESS;databaseName=EmpDB;encrypt=true;trustServerCertificate=true;";

private static final String USERNAME = "sa";

private static final String PASSWORD = "swamy";

private Connection connection;


private Singleton() throws SQLException {

connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

}


public static Singleton getInstance() throws SQLException {

if (instance == null || instance.connection.isClosed()) {

instance = new Singleton();

}

return instance;

}


public Connection getConnection() {

return connection;

}


public static void main(String[] args) {

try {

Singleton singleton = Singleton.getInstance();

System.out.println("Connected to SQL Server successfully!");

singleton.getConnection().close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

=========================================================

class singletonserial
{
private static singletonserial t;
private singletonserial()
      {
      }
      public static singletonserial serialized()
      {
            if(t==null)
            {
                  t=new singletonserial();
            }
            return t;

      }
@Override
      public Object clone()
      {
            return this;
      }
      public static void main(String[] args)
      {
        singletonserial t1=singletonserial.serialized();
        singletonserial t2=singletonserial.serialized();
            System.out.println(t1);
            System.out.println(t2);
      }
}

======================================================

class singletonsync
{
private static singletonsync t;
private singletonsync()
      {
      }
      public static singletonsync syncronized()
      {
            if(t==null)
            {
                  t=new singletonsync();
            }
            return t;
      }
@Override
      public Object clone()
      {
            return this;
      }
      public static void main(String[] args)
      {
        singletonsync t1=singletonsync.syncronized();
        singletonsync t2=singletonsync.syncronized();
            System.out.println(t1);
            System.out.println(t2);
      }
}
====================================================
By extending RuntimeException, you can create unchecked exception:

class TooYoungException extends RuntimeException {
TooYoungException(String s) {
super(s);
}
}

class TooOldException extends RuntimeException {
TooOldException(String s) {
super(s);
}
}

class CustomUncheckedExceptionDemo {
public static void main(String arg[]) {
int age = Integer.parseInt(arg[0]);
if (age > 60) {
throw new TooOldException("Younger age is already over");
} else if (age < 18) {
throw new TooYoungException("Please wait some more time");
}
System.out.println("Thanks for register");
}
}
=========================================
By extending Exception, you can create a checked exception:
// A Class that represents use-defined expception 
class MyException extends Exception {
public MyException(String s) {
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException
public class Main {
// Driver Program
public static void main(String args[]) {
try {
// Throw an object of user defined exception
throw new MyException("JavaJava");
} catch (MyException ex) {
System.out.println("Caught");

// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}
==============================

The constructor of Exception class can also be called without a parameter and call to super is not mandatory.
// A Class that represents use-defined expception
class MyException extends Exception
{
  
}
  
// A Class that uses above MyException
public class setText
{
    // Driver Program
    public static void main(String args[])
    {
        try
        {
            // Throw an object of user defined exception
            throw new MyException();
        }
        catch (MyException ex)
        {
            System.out.println("Caught");
            System.out.println(ex.getMessage());
        }
    }
}

No comments:

Post a Comment