thinkjava2

Java for PLSQL programmers

Hi ! If in the past years you have been a core PLSQL programmer like me, then this post is for you. What if suddenly you had to return to develop Java ? Where would you begin ?  I’ll start by remembering you of some basic concepts, and then quickly go through some Java Platform concepts.  Finally , you’ll install a developing environment and re-start coding !

Please note that I’m assuming you already programmed in JAVA a long time ago, and therefore I may skip some concepts that could be important for true beginners.

The Object Oriented Programming(OOP) concepts

The OOP concept leads the programmer to place data where it is not directly accessible by the rest of the program. The data is accessed by calling functions, or methods, which can be bundled in with the data or inherited from “class objects”.But what is an object ? An object is a “thing” that can perform a set of related activities. This set of related activities, is what defines the object behavior. An object is just an instance of a class. Using java terminology in the code snippet bellow,

Car ford = new Car();

the object ford is just an instance of class Car.

An object-oriented program may well contain multiple copies of each type of object, one for each of the real-world objects the program is dealing with. For instance, using the example above, there could be one car brand object for each real-world car.Each copy of the car brand object would be alike in the methods it offers for manipulating or reading its data, but the data inside each object would differ, reflecting the different history of each car brand.

In PLSQL the most similar thing we have to objects is the type object where we can declare member functions . These member functions can then be used to perform actions.

A class is just a representation of a type of object. A software system may consist of many classes.  In order to manage the classes, and to reduce the complexity, we can use several techniques, like  Encapsulation, Abstraction, Inheritance, and Polymorphism. These are  the four main Object  Oriented  Programming concepts.

1.Inheritance

Inheritance is the ability of a new class to be created, from an existing class by extending it. When this happens, the child class inherits the properties of the parent class.

PLSQL supports a single-inheritance model, where you can define subtypes of object types. These subtypes contain all the attributes and methods of the parent type. You can define whether or not subtypes can be derived from a particular type. You can also define types and methods that cannot be instantiated directly only by declaring subtypes that instantiate them.

I’m now going to give you some examples of this.First let’s start by creating a supertype(or parent type) from which several subtypes will be derived.

 CREATE TYPE Person as OBJECT (age NUMBER,
                                    name VARCHAR2(30) ,
                                    address VARCHAR2(100))
                                    NOT FINAL ;

Now let’s create a subtype with all the attributes of the parent type

 CREATE TYPE Student UNDER Person ( department VARCHAR2(30),
                                        university VARCHAR2(30))
                                        NOT FINAL ;

Our Student type is declared as NOT FINAL so we can further derive it

 CREATE TYPE PartTimeStudent UNDER STUDENT (workhours NUMBER) 

We can now write a small program to test our types :

declare
  firstPerson Person := Person(age => 31,name => 'John',address => 'NY');

 freshman    Student := Student(Age => 31,Name => 'Peter',Address => 'NY',
                          department => 'Engineering',
                          university => 'NY University');

  worker    PartTimeStudent := PartTimeStudent(Age => 29,Name => 'Alfred',
                                 Address => 'NY', department => 'Engineering',
                                 university => 'NY University',
                                 workhours => 30);
begin
  dbms_output.put_line('Name = '||firstPerson.name ||' Age = ' || firstPerson.age ||
                       ' Address = ' || firstPerson.address);

  dbms_output.put_line('Name = '||freshman.name || ' Age = '|| freshman.age || ' Address = '||
                        freshman.address || ' Department = '|| freshman.department ||
                        ' University = '|| freshman.university);

  dbms_output.put_line('Name = '||worker.name || ' Age = '|| worker.age || ' Address = '||
                       worker.address ||    ' Department = '|| worker.department ||
                      ' University = '|| worker.university ||
                      ' WorkHours = ' || worker.workhours);

end;

This would return :

Name = John Age = 31 Address = NY
Name = Peter Age = 31 Address = NY Department = Engineering
       University = NY University
Name = Alfred Age = 29 Address = NY Department = Engineering
       University = NY University WorkHours = 30

If we had created the Student type as FINAL , we could not have created the type PartTimeStudent UNDER Student, because Student could’t be instantiated. -Oracle would allow you to create the object PartTimeStudent anyway but would give you a error when you tried the 3rd dbms_output.

As you know the object type can have member functions/procedures. So if you want to hide a parent’s object procedure from its child , just declare the member procedure as final.

In JAVA we can use the keywords extends and implements to see the inheritance concept working. The basic difference is that extends is used with classes and implements is used with interfaces. Thanks to use of interfaces we no longer have the problem of multiple inheritance, that is, one class can only extend from another, but one class can implement multiple interfaces.

This syntax to create a class that extends other class is

  public class Test extends ParentTest {}; 

If you want to user the implements keyword you would have to create a special type of class name interface

  public interface One{};
  public interface Two{};

As you have seen I’ve create two interfaces, to use on the example below :

 public class Test implements One,Two {} ; 

2.Encapsulation

In PLSQL you can hide the implementation details from users but still give them all the information they need to use the package. Since they aren’t aware of the details, that means you can change them with minimal impact or risk. Packages also support private subprograms and variables which are available only to other subprograms within the package, and remain completely hidden and inaccessible to anything outside the package.

In JAVA encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.

Encapsulation can be seen as selective grid, that prevents the data from being randomly accessed by other code defined outside the class. Let’s look at the code bellow

public class Test{

   private String name;
   public String getName(){
      return name;
   }

   public void setName(String newName){
      name = newName;
   }
}

Imagine you want to set a value for the name variable. As the variable is declared as private , but you have public methods to change its value, you could use the following example :

public class RunTest{

   public static void main(String args[]){
      Test t1 = new Test();
      t1.setName("Helena");
      System.out.print("Name : " + t1.getName());
    }
}

As you have imagined by now, this example would output :

 Helena 

3.Abstraction

An abstraction is a high-level description or model of a real-world entity. Abstractions keep our daily lives manageable by suppressing irrelevant detail. For example, to drive a car, you need not know how its engine works. A simple interface consisting of a gearshift, steering wheel, accelerator, and brake, lets you use the car effectively. The details of what happens under the hood are not important for day-to-day driving.

There are several types of abstraction in PLSQL:

  • procedural abstraction when you hide the details of a complex algorithm by writing a procedure and passing it parameters. To try a different implementation, you simply replace the body of the procedure. Thanks to abstraction, programs that call the procedure need not be modified.
  • data abstraction when you specify the datatype of a variable. You’re using this type of abstraction whenever you use the %TYPE, %ROWTYPE, collections, records or other object types.

In JAVA an abstract class is one that cannot be instantiated.An abstract class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Example :

public abstract class Car
{
 private String carName;
 private String carType;
 private Double carPrice;

 public Car(String carName, String carType, Double carPrice)
 {
 System.out.println("Defining a car");
 this.carName = carName;
 this.carType = carType;
 this.carPrice = carPrice;
 }
 public void computeFirstPrice()
 {
 System.out.println("The car first price = "+carPrice+" €");
 }
}

If we tried and instantiated this class with

 Car cs = new Car("Ford","Focus",30000);

we would get a compile error. What we could do instead, is to extend the abstract class

public class CarSale extends Car
{
 private double price;
 public CarSale(String carName, String carType,  double price)
 {
    super(carName, carType, price);
    setCarPrice(price);
 }
 public double getCarPrice()
 {
    return price;
 }
 public void setCarPrice(double newPrice)
 {
    price = newPrice-3000;
 }
}

Despite the fact the we can’t instantiate the Car class, we can instantiate the CarSale class. This class would inherit all the methods from the Car class. If you write a small program to test this :

public class RunAbstract
{
 public static void main(String [] args)
 {
   CarSale cs = new CarSale("Ford", "Focus",30000);
   cs.computeFirstPrice();
   System.out.println("The car final price = "+cs.getCarPrice()+" €");
 }
}

The result would be :

The car first price = 30000 €
The car final price = 27000 €

4.Polymorphism

In OOP, Polymorphism is the ability of an object to take on many forms. The polymorphism is achieved by using many different techniques :

  • method overloading – the ability to define several methods with the same name
  • operator overloading – the case where operators like ‘+’, or ‘-‘ have different behavior based on its arguments
  • method overriding – is the process that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.

PLSQL lets you overload subprogram names and type methods. That is, you can use the same name for several different subprograms as long as their formal parameters differ in number, order, or datatype family.You can see an example of this bellow : 

DECLARE
  PROCEDURE print (arg INTEGER) IS
  BEGIN
          dbms_output.put_line('printed: ' || arg);
  END print;

PROCEDURE print (arg VARCHAR) IS
   BEGIN
           dbms_output.put_line('printed: ' || arg);
   END print;

BEGIN
    print(1);
    print('two');
END;

The example above would work fine. However, if we had created the second print procedure like this

 PROCEDURE print(arg NUMBER) IS ...

the compiler would return error because the subprograms should differ in datatype family.

JAVA allows for all the types of polymorphism described in the beginning of this topic.  Method overloading is very similar to PLSQL however it is a lot more powerful, because we can not only overload methods in the same class, but also overload methods that are declared in the parent class.This is called method overriding. Below you can find an example of this :


public class MyLogger {
   public void LogError(String logmessage){
 	System.out.println("MyLogger class message = " + logmessage);
    }
}
public class MyLogger2 extends MyLogger{
      public void LogError(Number logerror)   {
System.out.println("MyLogger2 class message = " + logerror);
      }
}
public class MyLogTest {

public static void main(String[] args) {
        MyLogger2 myl = new MyLogger2();
         myl.LogError("Hello");
         myl.LogError(1);
     }
}

This would output

   MyLogger class message = Hello
   MyLogger2 class message = 1

As a final example , I’ll show you how operator overloading works. This is a very simple concept.Look at the code snippet bellow :

public class MyTest {
public static void main(String[] args) {
System.out.println(1+1);
    System.out.println("Hi"+" there");
  }
}

The output of the code above would be :

 2
 Hi there

meaning that the plus operator can be used both to concatenate a String or to calculate the sum of 1+1.

The Java Platform

Both in Oracle and Java, you just write code and don’t care about the platform where it will run. On Oracle , you write PLSQL code and the PLSQL engine compiles and executes the PLSQL blocks and statements. The engine can be installed in an Oracle server or in an application development tool such as Oracle Forms.

The picture below tries to illustrate this concept:

PLSQL execution workflow

Remember that PLSQL can also have SQL blocks that are processed on SQL Statement Executor, located on the Oracle Server.

In the JAVA programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine(Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.

The picture below shows the JAVA execution execution workflow :

Java execution workflow

But JAVA is not only a programming language but also a platform that comprises many component technologies. The two principal products in the Java  platform are: Java Development Kit (JDK) and Java SE Runtime Environment (JRE).

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications. The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.

For illustration purposes only I’ve included a picture with the Java component technologies.

Java component technologies

I’m not going to detail every component on this picture. For that, you can go here. Anyway I believe you must know the difference between some core components and technologies and I’m going to explain some here.

1.Java vs J2EE

Java is both a language and a platform. J2EE is an implementation of the Java language used for web-based applications or network based applications. The runtime and libraries that comprise the Java platform come in three flavours:

  • Java SE – comprises the libraries shown in the picture above
  • Java EE – includes all the SE libraries plus Enterprise Java Beans(EJB), JSP,Servlets, JSF and others
  • Java ME – includes most of SE libraries plus APIs for handheld devices

2.JSP vs Servlets

Servlets and Jsp are both web components. A servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server’s servlet engine, servicing client requests forwarded to it through the server. A JSP page contains a mixture of HTML, pieces of Java code, JSP elements, and JSP directives. The elements in a JSP will generally be compiled  into a servlet.

The advantage of Java Server Pages is that they are document-centric. Servlets, on the other hand, look and act like programs. Servlets are therefore best suited for processing requests and handling the business logic while Jsp are suitable for content generating .

3.Enterprise Java Beans vs Java Beans

Javabeans are reusable components developed  for the client side and can be used with JSP/servlets.  EJB components are serverside.

JavaBeans features list :

  • may be visible or nonvisible at runtime
  • primarily intended to run on the client side
  • can be composed together into applet applications
  • have an external interface called “properties interface” which allows a builder tool to interpret the functionality of the bean
  • are not typed

EJB features list :

  • nonvisual remote object
  • remotely executable components or business objects that can be deployed only on the server
  • doesn’t build upon nor extends the original JavaBean specification
  • have a deployment descriptor that describes its functionality to an external builder tool or IDE
  • EJBs are of two types : session beans(short-lived, represents a single conversation with the client) and entity beans(long-lived, encapsulates persistent business data, like a row in a database)

4. Java Server Faces(JSF) vs JSP

JSF is a standard framework,  that makes it easy to build user interfaces for java web applications  by assembling reusable components in a page. You can think of  JSF framework as a toolbox  that is full of  ready to use components.

JSF applications are event driven. You typically embed components in a JSP page using custom tags defined by JSF technology and use the framework to handle navigation from one page to another. Components can be nested within another component , for example, input box, button in a form.

JSP are used to help software developers serve dynamically generated web pages (such as HTMLand XML) as well as other document types pertinent to the development of interactive web content. JSP are typically compiled as Servlets and allow Java code and specific predefined actions to communicate with static web markup content.

Hello world…again !!!

By now I hope you already have a good glimpse of the Java world. So nothing better to kickstart than to build the “Hello world…again” standalone application.

1. Choose the java distribution

First you should choose your Java distribution. Well, if a standalone hello world is all you want to do, then just download the latest JDK and you’re ready to go. You can download it from here.

2. Choose the development platform

Well, for a simple standalone application you really don’t need a development platform. Of course you’ll want to play around more, so why sit and wait when we can download the ONE platform : Eclipse ! Try the bundle “Eclipse for Java Developers” that you can download from here.

3. Hello world…again !

After installing Java and Eclipse , all you have to write your “Hello world…again!” standalone application is :


class Hello {

public static void main(String[] args) {
   System.out.println("Hello world...again!")
}

}

And your console should display :

Hello world...again !!

Final thoughts

Hope you enjoyed this reading as much as I enjoyed writing it. I’m sure a lot more could be said to compare both platforms and to put Java functionality in evidence, but I’ll leave that to the moment when I enter my next Java project.

Feel free to leave a comment ! I promise to answer as soon as possible.

References

[1] Oracle Blog; OOP in PLSQL:YEP , http://thinkoracle.blogspot.com/2005/06/oop-in-plsql-yep.html

[2]  PLSQL User’s Guide and Reference Release 9.0.1 ; PLSQL Object types,  http://download.oracle.com/docs/cd/A91202_01/901_doc/appdev.901/a89856/10_objs.htm

[3] PLSQL User’s Guide and Reference Release 9.0.1 ; PLSQL Subprograms  http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96624/08_subs.htm

[4] PLSQL User’s Guide and Reference Release 10g Release 2; PLSQL Object types,  http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/objects.htm#i12884

[5] Tutorials point, Java – Polymorphism , http://www.tutorialspoint.com/java/java_polymorphism.htm

[6] Burleson Consulting , Overloading method functions and procedures, http://www.dba-oracle.com/t_overloading_functions_stored_procedures.htm

[7] The Code Project ;Introduction to OOP Concepts, http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx#OOP

[8] Wikipedia; OOP Concepts , http://en.wikipedia.org/wiki/Object-oriented_programming

[9] Java SE ; Java SE 7 Documentation ; http://download.oracle.com/javase/7/docs/index.html

[10] Tutorials Point ; Java Encapsulation concepts , http://www.tutorialspoint.com/java/java_encapsulation.htm

[11] Java SE; Java Language Concepts , http://download.oracle.com/javase/7/docs/index.html

[12] Java SE; Java Language Definition , http://download.oracle.com/javase/tutorial/getStarted/intro/definition.html

[13] Servlets vs JSP’s , http://www.devx.com/tips/Tip/25217

[14] Difference between JSP and Servlets, http://www.differencebetween.net/technology/difference-between-jsp-and-servlet/

[15] The Java Tutorials ; About the Java Technology ; http://download.oracle.com/javase/tutorial/getStarted/intro/definition.html