Sunday, 29 April 2018

Java and OOPS concepts

Java is an object oriented programming language which can be downloaded and installed in your local Machine from java.com


To explain java binaries and tools requires block diagram which gives clear picture. For now I brief few important tools.

  • JDK - java development toolkit
  • JVM - Java virtual machine
  • JRE - Java Run time environment
From oracle site we can download JDK which is shipped along with JVM and JRM. Mostly java programmers need the JDK. For end users JRE alone is enough.

Basic OOPS characteristics are

Inheritance

Encapsulation

Abstraction

and Polymorphism

The above concepts collectively makes application software extendable and changeable with less effort.
Also helps in Developing design patterns. Design patterns gives solutions for common challenges usually a programmer faces while development applications.
Factory design pattern, Abstract design pattern, Builder pattern etc. I explain these Design patterns in another article.

Inheritance:
Inheritance is all about reusing one class behavior and members in it's child class. In java terminology these classes are called as super class and sub class. If class B extends class A then, class A becomes super class and class B becomes class A's sub class.

public class A{
  public A(){
 }
   -------
}
public class B extends A{
   public B(){
    } 
    -------
}   
Encapsulation:
Encapsulation is a technique of putting the source code all together within a unit. Java uses class and interface as keywords to represent unit. Data Hiding is one of the buzzwords which is possible only with implementation of Encapsulation in the program.

Abstraction:
Abstraction is the concept of hiding the irrelevant data from client/user visibility. To implement this feature java uses abstract keyword. this can be be prefixed to a class and methods. Once the class is abstract class then it's object can not be created. And id one or all methods of same class are followed by abstract keyword it can not be implemented.
The point here is java programming language gives implementation freedom to the developers where ever expected.
Sometimes java program is written to a another programmer rather a end user. Usually this code is called Application programming interface in short API. When a programmer writes a program with the intention to be used by another programmer, He/She may not need all the details [line by line] instruction's description is not required. Right?
The punch line is abstraction helps in showing only relevant data to the client of our program.
One of the mostly used design pattern is abstract factory design pattern.

Polymorphism:
In generic terminology poly means many morph means forms. It means many forms of a single method names.
Polymorphism can be achieved within the class or using inheritance i.e extends keyword.

Overloading and overriding:

Overloading rules:
within the class a same method can be duplicated but accepts different arguments and returns different result
  1.       Number of arguments must be different
  2. Or  Sequence of arguments must be different
  3. Or  Type of the arguments must be different.
Uses:
Let us take a method .
     int add(int a, int b){
        return a+b;
     }

Now let us overload this method to add decimal values
 float add(float a, float b){
     return a+b;
 }
Now based on the arguments passed to the add() respect add() method will be invoked.
Overriding:
Overriding is possible only by using inheritance.For an instance super class has add(int a, int b). and sub class also needs add operation but computes differently. Then programmer simply overrides the add() of super class overrides the add() with his new implementation. 
public class SuperClass{

  int add(int a, int b){
       ....
   }
}

public Subclass extends SuperClass{
@Overrides
int add(int a, int b){
// computes his own add operation
}
} 
In next article I write about tools of JDK and JRE and internals of JVM Java Virtual Machine.

Please click the link for more good look and feel and elegant font

Happy Coding. ;-)


Wednesday, 31 January 2018

Core Java: Immutable objects and mutable objects with an example

Immutable objects and mutable objects with an example 


In object oriented programming language in short OOPS, every problem, precisely every requirement is viewed as an object. Understanding the problem in this point of view brings many good things possible in programming like encapsulation, abstraction, polymorphism and inheritance. Anyways this post is not intended for describing benefits of OOPS.

Object could be any thing. Let us take Car for an instance. Basically car is an object and it has name, wheels, metal body, engine, maximum speed,  gear box etc as properties.

Let us consider the car name is Ferrari, maximum speed is 200 km per hr with 6 gears. While driving the car driver can change the speed of the car and change the gear etc.
So while car is running it's current speed, current gear are considered to be state of the object.
The current speed can be changed using accelerator and gear can be changed using gear box. These can be considered as behavior of the car object. Of course car has a name as well.

 Every object has 3 characteristics they are State, Behavior and Name. 

In our example Ferrari is name of the object. Number of gears, current gear, current speed are State and accelerator and gear box decides the behavior of the car object. In java language object's reference name is name of object and methods which decides state are behavior.  

ImmutableObject ferrari = new ImmutableObject("Ferrari", 200, "Red");

             1. new operator creates the object
             2. ferrari is name of object
             3. Ferrari, 200, and Red are State of object

Objects based upon it's behavior can be categorized into two types. They are 
              1. Immutable objects and 
              2. Mutable objects


Mutable and Immutable objects



Mutable object's state can be changed at run time, where as immutable object's state can not be changed. String class is the ideal example for immutable objects. 
    
The state of an object can be decided at it's creation time or at run time or at both times. If state is decided at creation time and it is restricted not be changed at run time, this object is considered to be an  immutable object. If this can be changed at run time, it is called as mutable object.

If car is automatic [no gears] and it's speed can not be changed at any time, then it is immutable car object.  

Below program creates immutable objects:




01  public final class ImmutableObject {
02
03  private String name;
04
05  private int maxSpeed;
06
07  private String color;
08
09  /**
10  * @param name
11  *            holds car name
12  * @param maxSpeed
13  *            holds maximum speed of the car
14  * @param color
15  *            holds color of car
16  */
17  public ImmutableObject(String name, int maxSpeed, String color) {
18  this.name = name;
19  this.maxSpeed = maxSpeed;
20  this.color = color;
21  }
22
23  public String getName() {
24  return name;
25  }
26
27  public int getMaxSpeed() {
28  return maxSpeed;
29  }
30
31  public String getColor() {
32  return color;
33  }
34
35  public static void main(String[] args) {
36  ImmutableObject ferrari = new ImmutableObject("Ferrari", 200, "Red");
37  System.out.println("Car name: " + ferrari.getName());
38  System.out.println("Car color:" + ferrari.getColor());
39  System.out.println("Car maximum speed:" + ferrari.getMaxSpeed());
40  System.out.println();
41
42  ImmutableObject anotherCar = new ImmutableObject("BMW", 180, "White");
43  System.out.println("Car name: " + anotherCar.getName());
44  System.out.println("Car color:" + anotherCar.getColor());
45  System.out.println("Car maximum speed:" + anotherCar.getMaxSpeed());
46  }
47  }
48

Output:

Car name: Ferrari
Car color:Red
Car maximum speed:200

Car name: BMW
Car color:White
Car maximum speed:180

Explanation


Line 1: First and fore most rule is to make your class final class.

Line 3 to Line 7: All variables are private variables. private access modifier restrics usage of members within the class

Note: Do not use other classes as data types of your instance variables which are mutable in behavior. All of our example variables are of String type. String is immutable. See API document of String class for more information.   


Line 17: Creates parameterised constructor with state which can not be changed at run time

Line 23 to Line 33: Create only those methods which shares it's state to the other classes. As we did in our example ImmutableObject. Allows only getter methods and no setter methods at all.


Line 36 to Line 42: Finally, create 2 objects ferrari and another car with different state which can not be changed at run time..

Now, let us change the same class which allows creating mutable objects:

01
02 public class MutableObject {
03
04 private String name;
05
06 private int maxSpeed;
07
08 private String color;
09
10 private int currentGear;
11
12 private int currentSpeed;
13
14 /**
15 * @param name
16 *            holds car name
17 * @param maxSpeed
18 *            holds maximum speed of the car
19 * @param color
20 *            holds color of car
21 */
22 public MutableObject(String name, int maxSpeed, String color) {
23 this.name = name;
24 this.maxSpeed = maxSpeed;
25 this.color = color;
26 }
27
28 public String getName() {
29 return name;
30 }
31
32 public int getMaxSpeed() {
33 return maxSpeed;
34 }
35
36 public int getCurrentGear() {
37 return currentGear;
38 }
39
40 public void setCurrentGear(int currentGear) {
41 this.currentGear = currentGear;
42 }
43
44 public int getCurrentSpeed() {
45 return currentSpeed;
46 }
47
48 public void setCurrentSpeed(int currentSpeed) {
49 this.currentSpeed = currentSpeed;
50 }
51
52 public String getColor() {
53 return color;
54 }
55
56 public static void main(String[] args) {
57 MutableObject ferrari = new MutableObject("Ferrari", 200, "Red");
58 System.out.println("Car name: " + ferrari.getName());
59 System.out.println("Car colo: " + ferrari.getColor());
60 System.out.println("Car maximum speed:" + ferrari.getMaxSpeed());
61
62 ferrari.setCurrentGear(5);
63 ferrari.setCurrentSpeed(150);
64 System.out.println(String.format("Current speed is %s and current gear is %s \n", ferrari.getCurrentSpeed(), ferrari.getCurrentGear()));
65
66
67 ferrari.setCurrentGear(1);
68 ferrari.setCurrentSpeed(10);
69 System.out.println(String.format("Changed state at run time!.. \nCurrent speed is %s and current gear is %s ", ferrari.getCurrentSpeed(), ferrari.getCurrentGear()));
70
71
72 System.out.println();
73
74 }
75}
76

Output:


Car name: Ferrari
Car colo: Red
Car maximum speed:200
Current speed is 150 and current gear is 5 

Changed state at run time!.. 
Current speed is 10 and current gear is 1 


Explanation

  

Line 2: Remove final keyword. This makes the class extendable using extend keyword

Line 10 to Line 12: Introduced new variables which adds new information to the state of object

Line 40 and Line 48: Introduced new setter methods which changes state at run time.

Line 57: Finally, create the ferrari object and change it's state run time by calling different setter methods.

Line 62 to Line 72: Changes the state by calling setters on member variables.  

Few more details about immutable objects:


  • It is always good practice to use immutable objects in our application especially in concurrent apps where ever applicable
  • Immutable objects ensures correct results/output always in all environments like multi threading environment, collection framework.
  • HashMap<key, value> always requires immutable object as key. Otherwise it behaves in undetermined way.
  • Consider cloning when creating immutable classes. I will post another article about importance of deep cloning and shallow copy in details in near future.
  • Cache memory implementation uses immutable objects 
  • java.lang.String is the most used immutable class in java

    .

Monday, 29 January 2018

Swing JLabel demo with example

This article is continuation of previous post JFrame usage demo. Please read it before continuing.

This post uses the same example code shown in JFrame usage demo with JLabel changes and introduces layout manager BorderLayout.

Layout Manager:

Layout manager is responsible to arrange components on containers. Usually every swing container is created with a default layout manager but can be changed with setLayout() api. For example JFrame uses BorderLayout as default layout amanger.

Java program for JLabel


2   import java.awt.BorderLayout;
3   import java.awt.Color;
4   import java.awt.Font;

6   import javax.swing.JFrame;
7   import javax.swing.JLabel;
8   import javax.swing.SwingUtilities;

10  /**
11   *
12   * Simple class to demonstrate JLabel of swing toolkit
13   *
14   * @author Nagasharath
15   *
16   */
17  public class LabelDemo extends JFrame {
18
19  private final String title = "It's all abt java!...  ";
20
21  private JLabel label;
22
23  /**
24  * set properties of the main window. Title, size of frame and position/location
25  */
26  public LabelDemo() {
27  this.setTitle(title);
28  this.setSize(300, 200);
29  this.setLocationRelativeTo(null);
30  initComponents();
31  }
32
33  /**
34  * instantiates controls controls.
35  *
36  */
37  private void initComponents() {
38  BorderLayout layout = new BorderLayout(20, 10);
39  this.setLayout(layout);
40
41  label = new JLabel("java-gui.blogspot.com");
42  label.setForeground(Color.RED);
43  label.setFont(new Font(Font.MONOSPACED, Font.BOLD, 25));
44  this.getContentPane().add(label, BorderLayout.CENTER);
45  }
46
47  public static void main(String[] args) {
48
49  Runnable r = () -> {
50  LabelDemo demo = new LabelDemo();
51  demo.setVisible(true);
52  };
53  SwingUtilities.invokeLater(r);
54  }
55  }
56


Line 21: Introduced new variable of type JLabel

Line 38 and Line 39: Used BorderLayout as layout manager to arrange label component on JFrame container

Line 41: Instantiated label with a text of String type.

Line 42 and Line 43:  label properties like foreground color, font style, size, type and background etc are specified

Line 44:  Finally added this label to the JFrame using add().

Output:


JFrme with JLabel

Popular posts

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...