Quick Java object oriented review

Default featured post

Few weeks ago I was reviewing my Java programming knowledge especially in object oriented area. After C# review post which I posted before, I wrote small but I guess useful review for Java as well. As mentioned earlier the main concern of this post is reminding object oriented knowledge in Java. Therefore, it will not be suitable for those who do not have any knowledge in Java. For inexperienced people, it is highly recommended to take a look at Java syntax and basics first. Finally, in the last section of this post, basic Java Swing is discussed and those who do not want to read about Java GUI, that part is option.

In Java it is possible to import static methods of the class with using Static word before importing package(s).

import static java.util;
view raw Test.java hosted with ❤ by GitHub

Final variable is look like const variable with this difference that it does not need to be initialized on declaration time and it can be initialized when is necessary, but in the case of constant it has to initialize when it’s declared.

private final int x;
public construct() {
x=10;
}
view raw Test.java hosted with ❤ by GitHub

After first initialization it is not possible to change value of Final variable and if we attempt to change it, we will face with the compilation error.

It’s also better to define Final variable as Static since once it can be initialized and not more than that.

In addition to what mentioned above, it’s possible to define a method as Final. Final method cannot be overridden in sub classes. In fact, they are inherited to the sub classes but it’s not possible to override them.

public final int MyFiMeth() {
}
view raw Test.java hosted with ❤ by GitHub

It’s possible in Java to declare packages and utilize them in other applications which this process is called as reusing the code. For creating your own package you should follow below steps:

  • When creating a class file you should declare your custom package name in the first line before writing any codes like below,
package MyPack.example1;
view raw Test.java hosted with ❤ by GitHub
  • Then in the next step, the created class (package) is needed to compile with the following command,
$ javac –d . MyPackFileName.java
view raw Test.java hosted with ❤ by GitHub

DOT in the above example creates the package file on the current directory since compiling package causes creating new files.

  • Finally, the package like other packages has to be imported on the code which wants to use the created package.
import MyPack.example1;
view raw Test.java hosted with ❤ by GitHub

In Java inheritance possible with the use of word Extends such as below example.

class Base {
private int x;
private int y;
public setXY(int x, int y) {
this.x = x;
this.y = y;
}
}
class SubClass extends myBase {
public setXY(int x, int y) {
super.setXY(x,y);
}
}
view raw Test.java hosted with ❤ by GitHub

The word Super is used in inheritance and when subclass wants to call super class method or variable which the same name is existed in the subclass. Therefore, it’s used to distinguish between calling the subclass method which has the same name with the super class name as mentioned in the previous example. Moreover, if we want to access to the constructor of the super class we can just use the word super like a function and pass parameter(s) to it to access to that constructor.
In Java we can compare two Instances (Objects) with each other with the use of Equals method like below,

MyOb1.equals(MyOb2);
view raw test.sh hosted with ❤ by GitHub

In Java for displaying messages and interaction boxes one Abstract class is existed which is called as JoptionPane. This class contains various methods which each some of them suggest various types of message boxes, input boxes.

For instance, showInputDialog presents dialog box to the user and the user is able to enter something there.

Another one is ShowMessageDialog which is simply display one message box with OK button. For more flexible message box also showConfirmDialog could be utilized which contains variety types of dialog boxes like:

  • OK/Cancel
  • Yes/No/Cancel
  • Abort/Retry/Ignore, etc.

Using JoptionPane is like below:

JoptionPane.showConfirmDialog(null, message, title, option);
view raw Test.java hosted with ❤ by GitHub

In Java graphic user interface designing the first and basic layer or in other word the lowest layer is JFrame and above that is Jpanel which is added inside of the Jframe with the use of add method such as below example.

Jframe jf = new Jframe();
Jpanel jp = new Jpanel();
jf.add(jp);
jf.size(250, 250);
jf.setVisible(true);
view raw Test.java hosted with ❤ by GitHub

In the above sample code, panel will cover up the entire frame since the size of the panel has not been set. In order to put various panels together, the size of each and also the place or location should be determined explicitly. Additionally, in the case of the Jframe, the location could be set with utilizing setLocation method.

The use of Abstract class is to define one super class and other classes inherit from this class and complete Abstract class implementation. In fact, an abstract class is not complete class and some methods are needed to be implemented which can be done with the use of inheritance and those incomplete methods are implemented in sub classes. If a class is defined as Abstract, it cannot be instantiate. Defining abstract class is looks like below,

abstract class MyAbClass {
}
view raw Test.java hosted with ❤ by GitHub

In addition to that, we could define Abstract methods in Java. Abstract methods cannot have implementation and they are just definition and the real implementation should be done in the sub classes. Furthermore, Abstract method has to be defined inside of Abstract class and it is not possible to define Abstract method in the body of non-abstract classes. Defining abstract method is looks like following,

public MyAbMethod(int x, int y);
view raw Test.java hosted with ❤ by GitHub

Like C# in Java we also can define Interface. In fact interface does not contain any types of implementation and it just has definition of some methods (even not fields) that are common among some other classes and can be used by those classes. Look at the following example for defining an Interface.

public interface MyInterface {
public int MyIntMethod(int x, int y);
}
view raw Test.java hosted with ❤ by GitHub

When we want to implement the methods inside of the interface, we should use the word “Implements” in front of the class. Additionally, interfaces cannot contain Private methods. Public and Abstract only permitted. Below example demonstrates how to implement above interface in a class.

public class MyClass implements MyInterface {
public int MyIntMethod(int z, int zz) {
return z + zz;
}
}
view raw Test.java hosted with ❤ by GitHub

@Override is annotation in Java programming and @Override is used when we want to override a method either from superclass or interface in the subclass. When we add it before override name of the method, it checks that the method is an override and causes a compile error if the method is not found in one of the parent classes or implemented interfaces.

In Java it’s possible to mix implementing of an interface and inheritance at the same class at the same time but at first class should be extended and after that implemented when subclass is defined like below example,

public interface MyInterface {
public void calc();
public int rt();
}
public class MySuperClass {
public int sum(int x, int y) {
return y + x;
}
public int minus(int x, int y) {
return x – y;
}
}
public class MySubclass extends MySuperClass implements MyInterface {
private int x;
private int x;
@Override
public int sum(int x, int y) {
this.x = x;
this.y = y;
return x + y;
}
@Override
public int rt() {
return this.x * this.y;
}
}
view raw Test.java hosted with ❤ by GitHub

Like C#, Java also supports try and catch statement. Take a look at below example,

try {
int x = 0;
Scanner input = new Scanner(System.in);
x = input.nextInt();
} catch {
System.out.println("Error happened!");
}
view raw Test.java hosted with ❤ by GitHub

Again like C#, Java has Object type which is the base type of each class and instance and can hold anything either primitive data type or even user defined data types.

Object ob = new Object();
Ob = 10;
view raw Test.java hosted with ❤ by GitHub

In fact, the default type of the ArrayList, Stack, Queue, HashTable are all Objects and with the use of Generic, we could specify the exact type in order to avoid adding non-related objects.

On the time of designing GUI in Java, if we want to terminate application when the main frame (Jframe) is closed then the following line should be added to the frame which we want to terminates the application with its closure,

MyFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
view raw Test.java hosted with ❤ by GitHub

If we want to call non-static method inside static method and both methods are located in the same class, then still we need to make an instance of from the class and then call non-static method. Otherwise, the non-static method should be defined static or vice versa.

If you want your Java GUI looks native for each operating system and changes the look based on the OS is running, you should add below lines to your code.

try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
//Your exception handling code.
}
view raw Test.java hosted with ❤ by GitHub

Keep in your mind that the above code might not work for every OS and as a result, the application might not load at all. So use it carefully.

For creating Menu on Jframe see the following instruction,

  • Create JFrame and set size,
JFrame jf = new JFrame("Frame1");
Jf.setPreferredSize(new Dimension(200, 200));
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
view raw Test.java hosted with ❤ by GitHub
  • Then JMenu which can hold JMenuItems should be created,
JMenu jm = new JMenu("File Menu");
jm.setMnemonic('F');
view raw Test.java hosted with ❤ by GitHub
  • In the next step JMenuItems should be created and items should be added there,
JMenuItem jmt = new JMenuItem("Open");
JMenuItem jmt1 = new JMenuItem("Close");
jmt.setMnemonic('O');
jmt1.setMnemonic('C');
jm.add(jmt);
jm.add(jmt1);
view raw Test.java hosted with ❤ by GitHub
  • After finishing menu creation, now the menu should a menu bar should be created and the menu should be added there,
JMenuBar jmb = new JMenuBar();
jmb.add(jm);
view raw Test.java hosted with ❤ by GitHub
  • Finally, created menu bar should be added to the frame which firstly is created and then finally show the frame.
jf.setJMenuBar(jmb);
jf.pack();
jf.setVisible(ture);
view raw Test.java hosted with ❤ by GitHub

Overall for handling events and actions following Imports are needed.

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent
import java.awt.event.MouseListener;
view raw Test.java hosted with ❤ by GitHub

In order to avoid override all methods of Listeners (Key, Mouse, Action) we could Extends (Key, Mouse, Action) Adapter instead of Implements (Key, Mouse, Action) Listener. For accessing to those Adapter class, following Libraries should be imported.

import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
view raw Test.java hosted with ❤ by GitHub

For placing items in the frame without filling the entire frames, the frame layout should be changed to following,

MyFrame.setLayout(new FlowLayout());
view raw Test.java hosted with ❤ by GitHub

In the above Layout firstly, the items are placed side by side of each other and if there will be no space, the item is placed in the new line (below).

For knowing more about GUI programming in Java please refer to Java books which are available at market, Java for beginner (Apress) and Java hot to program (Deitel) chapter 14, 15, 25 are highly recommended for beginners.

In Java it’s possible to just create object from a class without dedicating a name to it or in other word, the created object would be input parameter of another object like following example,

MyClass mc = new MyClass();
MethodNeedsObject(mc);
// We can change the above example to below,
MethodNeedsObject(new MyClass());
// For defining anonymous class see the follow example,
MethodNeedsObject( new MyClass() {
public void MyMethod(int x, int y) {
//Do some operations;
}
});
view raw Test.java hosted with ❤ by GitHub

Finally block is mostly located after catch block and it executes whether exception occurs or not. In fact some codes are put there to ensure that they will execute. In one condition Finally block is not executed and that occur when the application terminated in either try or catch block. The code inside of Finally block mostly related to resource releasing.

It is possible to throw exception for different conditions when it is needed. For instance, a user should input a number and we want to warn him if the number is less than 1. Therefore, the code would be like the following example,

Scanner input = new Scanner(System.in);
int x = 0;
try {
x = input.nextInt();
if(x < 1) {
throw new InputMismatchException();
}
} catch(InputMismatchException e) {
System.out.println("You input wrong number!");
}
view raw Test.java hosted with ❤ by GitHub

Type of exception could be different based on your needs. For instance, you can use IOException, MissingResourceException, MissingFormatWidthException, etc.