Search Logic Blocks

Saturday, August 22, 2020

Java: How to access superclass members

We have already seen how to call superclass constructors in the last post - How to access superclass constructors. Subclass instances / objects can access all the non-private superclass members (variables and methods) directly. But if the methods are overridden, the subclass instances call only the overridden subclass methods. But if the program needs to call superclass method, subclass methods can call them by using a keyword super -
public class Shape {
final static double PI = Math.PI;
double width = 0;
double height = 0;
String borderColor = "Blue";

// Superclass constructors
Shape() {
this.width = 5;
this.height = 8;
}

Shape(
double width, double height) {
this.width = width;
this.height = height;
}

// Returns the text telling what shape it is
public String whatShape() {
return "";
}

// Returns the area of the shape
public double area() {
return 0.0;
}

public void setColor(String color) {
this.borderColor
= color;
}

}
public class Triangle extends Shape {
String fillColor;
// Triangle Constructor with no arguments
Triangle() {
super();
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
super();
this.fillColor = fillColor;
}

// Triangle Constructor with three arguments
Triangle(double width, double height, String fillColor) {
super(width, height);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle t = new Triangle(4, 6, "Yellow");
System.
out.println(t.width);
System.
out.println(t.height);
System.
out.println(t.fillColor);
System.out.println(t.borderColor);
}
}
In the above example, a new method setColor() is added to set the Shape class's bordercolor variable. And subclass Triangle hasn't overridden the method setColor(). The Triangle class instance calls the method setColor(), Triangle class doesn't have any method named as setColor(). So, the setColor() method from the superclass is called automatically. Here is the output -

4.0
6.0
Yellow
Blue

Overriding Methods
Let's override the method setColor() and then call the method from the subclass instance. In this case, the subclass version of the method setColor() is called. Here is the code and output.
public class Triangle extends Shape {
String
fillColor;
// Triangle Constructor with no arguments
Triangle() {
super();
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
super();
this.fillColor = fillColor;
}

// Triangle Constructor with three arguments
Triangle(double width, double height, String fillColor) {
super(width, height);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}

public void setColor(String color) {
this.fillColor = color;
}

}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle t = new Triangle(4, 6, "Yellow");
System.out.println(t.width);
System.out.println(t.height);
System.out.println(t.fillColor);
t.setColor("Green");
System.out.println(t.fillColor);
System.out.println(t.borderColor);

}
}
4.0
6.0
Yellow
Green
Blue

In above example, setColor() method in the subclass method is changing the fillcolor, not bordercolor. So, fillColor is Green and borderColor is same as blue.

Call superclass method from the overridden method
To call the superclass method from the subclass method, the keyword super is used. Here in the example, the following statement calls the superclass method setColor(). And the output is changed accordingly -
public class Triangle extends Shape {
String
fillColor;
// Triangle Constructor with no arguments
Triangle() {
super();
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
super();
this.fillColor = fillColor;
}

// Triangle Constructor with three arguments
Triangle(double width, double height, String fillColor) {
super(width, height);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}

public void setColor(String color) {
super.setColor(color);
this.fillColor = color;
}

}
4.0
6.0
Yellow
Green
Green

Superclass method can be called from any subclass method
To call the superclass methods, the method does not need to be overridden. Here in the following example,  a new method setDiffColor() is added, it passes two parameters - fillcolor and bordercolor. The superclass method is called to set bordercolor.
public class Triangle extends Shape {
String
fillColor;
// Triangle Constructor with no arguments
Triangle() {
super();
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
super();
this.fillColor = fillColor;
}

// Triangle Constructor with three arguments
Triangle(double width, double height, String fillColor) {
super(width, height);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}

public void setColor(String color) {
super.setColor(color);
this.fillColor = color;
}

public void setDiffColor(String fillcolor, String bordercolor) {
this.fillColor = fillcolor;
super.setColor(bordercolor);
}

}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle t = new Triangle(4, 6, "Yellow");
System.
out.println(t.width);
System.
out.println(t.height);
System.
out.println(t.fillColor);
t.setDiffColor("Green","Pink");
System.
out.println(t.fillColor);
System.
out.println(t.borderColor);
}
}
Here is the output -

4.0
6.0
Yellow
Green
Pink

All the code can be found at Github Link.

Wednesday, August 19, 2020

Java: How to access superclass constructors

As we have already discussed about inheritance earlier and we have also learnt about how to override the superclass methods in subclasses. Superclass is a common class, subclass can access all non-private members from the superclass and can also add new own members. Superclass non-private member variables can be accessed directly, but superclass constructors and non-private member methods can be accessed by using a keyword super. 

How to access Superclass constructor
If the subclass doesn't have any constructor and superclass has a constructor with no arguments, by default the superclass constructor method is invoked. Let's take the example Shape, Triangle and ShapesTest from earlier post and modify by adding two constructor methods -
public class Shape {
final static double PI = Math.PI;
double width = 0;
double height = 0;

// Superclass constructors
Shape() {
this.width = 5;
this.height = 8;
}

Shape(int width, int height) {
this.width = width;
this.height = height;
}

// Returns the text telling what shape it is
public String whatShape() {
return "";
}

// Returns the area of the shape
public double area() {
return 0.0;
}
}
public class Triangle extends Shape {
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle triangle = new Triangle();

System.out.println(triangle.whatShape());
System.out.println(triangle.width);
System.out.println(triangle.height);
}
}
In the above example, Shape class has two constructors and Triangle class doesn't have any constructor. But when an instance of Triangle class is created, superclass constructor is automatically called. Here is the output for above code -

Triangle
5.0
8.0

Let's add one new member variable and one constructor in subclass Triangle with no arguments. And also print the new member variable value in the ShapesTest class. We have added new member variable as fillColor and Triangle class constructor initializes fillColor as "Red" -
public class Triangle extends Shape {
String fillColor;
// Triangle Constructor with no arguments
Triangle() {
this.fillColor = "Red";
}
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle triangle = new Triangle();

System.out.println(triangle.whatShape());
System.out.println(triangle.width);
System.out.println(triangle.height);
System.out.println(triangle.fillColor);
}
}
In the above example, we have added one new member variable fillColor in subclass Triangle. When the new instance of Triangle class is created, superclass constructor is called automatically following by the subclass constructor with no arguments. Here is the output of above code -

Triangle
5.0
8.0
Red

Let's create another constructor in subclass with one argument to set value of the subclass member variable fillColor dynamically. Still, the superclass constructor (with no arguments) is called implicitly before calling the subclass constructor, and superclass member variables are initialized. Here is the code -
public class Triangle extends Shape {
String fillColor;
// Triangle Constructor with no arguments
Triangle() {
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
this.fillColor = fillColor;
}
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle triangle1 = new Triangle();

Triangle triangle2 = new Triangle("Blue");

System.out.println(triangle1.whatShape());
System.out.println(triangle1.width);
System.out.println(triangle1.height);
System.out.println(triangle1.fillColor);

System.out.println();
System.out.println(triangle2.whatShape());
System.out.println(triangle2.width);
System.out.println(triangle2.height);
System.out.println(triangle2.fillColor);
}
}
And the output is -

Triangle
5.0
8.0
Red

Triangle
5.0
8.0
Blue

But, if you are not sure if the superclass constructor is called, you can call it by using super() method. It will give the same result as above. Here is the code with subclass constructor with call to superclass constructor using super() method (note that superclass constructor call statement should be the first statement in the subclass constructor) -
public class Triangle extends Shape {
String fillColor;
// Triangle Constructor with no arguments
Triangle() {
super();
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
this.fillColor = fillColor;
}
// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
Only subclass Triangle is changed, and the output is same above -

Triangle
5.0
8.0
Red

Triangle
5.0
8.0
Blue

Let's add one more constructor in subclass which takes three arguments and calls superclass constructor method with two arguments. Here we will use again super() method but with two arguments. Here is the code - 
public class Triangle extends Shape {
String fillColor;
// Triangle Constructor with no arguments
Triangle() {
super();
this.fillColor = "Red";
}

// Triangle Constructor with one argument
Triangle(String fillColor) {
super();
this.fillColor = fillColor;
}

// Triangle Constructor with three arguments
Triangle(double width, double height, String fillColor) {
super(width, height);
this.fillColor = fillColor;
}

// Returns the text telling what shape it is
public String whatShape() {
return "Triangle";
}

// Returns the area of the shape - can access parent's declared variables
public double area() {
return Math.round((height * width / 2) * 100) / 100.0;
}
}
public class ShapesTest {
public static void main(String args[]) {
// Created a triangle shape
Triangle triangle1 = new Triangle();

Triangle triangle2 = new Triangle("Blue");

Triangle triangle3 = new Triangle(4, 6, "Purple");

System.out.println(triangle1.whatShape());
System.out.println(triangle1.width);
System.out.println(triangle1.height);
System.out.println(triangle1.fillColor);

System.out.println();
System.out.println(triangle2.whatShape());
System.out.println(triangle2.width);
System.out.println(triangle2.height);
System.out.println(triangle2.fillColor);

System.out.println();
System.out.println(triangle3.whatShape());
System.out.println(triangle3.width);
System.out.println(triangle3.height);
System.out.println(triangle3.fillColor);
}
}
Here is the output of above example -

Triangle
5.0
8.0
Red

Triangle
5.0
8.0
Blue

Triangle
4.0
6.0
Purple

Note that the super() method call is the first statement in subclass constructors. You can find code at Github Link.

Friday, August 14, 2020

Java: Static Initialization Block

What is a Block?

So far, we have written so many programs and in every program we have different kinds of blocks - class block, method block, loop block etc. Any code between opening parentheses and closing parentheses is called a block. And the variables declared in the block can not be accessed outside from the block. For ex:

class [class name] {

}

for(.....) {

}

We can have a block without any name like below :

{
    int x = 5;
}

And the variable x is not accessible outside from the block. Here is the example code -
public class Block {
public static void main(String args[]) {
int x = 10;
String str = "Block Example";
System.out.println("Value of x is : " + x);
System.out.println("This is : " + str);
{
int y = x + 5;
System.out.println("This is inside the block");
}
// System.out.println("Value of y is : " + y);
}
}
In the above code, commented code shows that the variable is declared in the block, so it can not be accessed outside from the block. Here is the output of above code -

Value of x is : 10
This is : Block Example
This is inside the block

What is an Initialization Block?

Initialization block, is the block of code used when initializing the class variables at the start of the class declaration. Mostly initialization block is used to assign the default values to class variables. The initialization block can have any valid Java statement. Here is the example of initialization block -
public class InitBlock {
int x;
int y;
static int z;

{
System.out.println("Initialization Block");
x = 10;
y = 15 + x;
z = 20;
System.out.println("Value of x is: " + x);
System.out.println("Value of y is: " + y);
}
}
public class InitBlockDemo {
public static void main(String args[]) {
InitBlock ib = new InitBlock();
System.out.println("value of z is: " + InitBlock.z);
}
}
In the above example, initialization block has the print statement. When the instance is created, the statements in initialization block are executed. Here is the output -

Initialization Block
Value of x is: 10
Value of y is: 25
value of z is: 20

What is Static Initialization Block?

We have already discussed about Static Variables, Static Methods, Static Inner Classes. We already know, that to access the static variables, methods and inner classes, there is no need to create the instance of the class. They can be accessed directly through class itself. And, we also know that the static methods and the static inner classes can access only the other static members of enclosing class, not non-static members.

Static initialization block is the initialization block which is used to initialize only the static class variables. It can not access non-static variables. Here is the conversion of above example into static initialization block example.
public class StaticInitBlock {
int x;
int y;
static int z;

static {
System.out.println("Static Initialization Block");
// x = 10;
// y = 15 + x;
z = 20;
// System.out.println("Value of x is: " + x);
// System.out.println("Value of y is: " + y);
System.out.println("Values x and y are not accessible in static block");
}
}
public class StaticInitBlockDemo {
public static void main(String args[]) {
System.out.println("value of z is: " + StaticInitBlock.z);
}
}
Here, the commented code in the above example shows that the non-static variables can not be initialized in the static initialization block. Here is the output -

Static Initialization Block
Values x and y are not accessible in static block
value of z is: 20

Here is the link for example code at Github.

Monday, August 10, 2020

Java: Static Inner Classes

Like a class can have both static and non-static variables, it can have static and non-static inner classes. We have already learnt about static variables and non-static variables. We have also learned about non-static inner class in earlier post - inner classes. As we know that static variables are class variables and they can be accessed directly through the class itself. We don't need to create the instance of class to access the static variable.

Static inner class is declared static same way as the static variables are declared using static keyword. Static inner class is also accessed through the outer class itself and its instance is created using new operator. Static inner class can only access static members of the enclosing class, not other members.
public class StaticClassDemo {
static int staticInt = 5;
int noStaticInt = 5;
static class staticInnerClass {
staticInnerClass() {
System.out.println("Creating Static Inner Class");
}

void printText() {
System.out.println("Inside Static Inner Class");
}

void getOuterClassData() {
System.out.println("Outer Class Static Variable staticInt = " + staticInt);

// Can't access non-static members
//System.out.println("Outer Class Non-Static Variable noStaticInt " + noStaticInt);
}
}

public static void main(String[] args) {
StaticClassDemo.staticInnerClass stClass = new StaticClassDemo.staticInnerClass();

stClass.printText();
stClass.getOuterClassData();
}
}
Note: The code can be accessed here at Github Link.

Saturday, August 8, 2020

Java: Anonymous Classes

We have discussed inner classes and local classes - inner class is a class in a class, local class is a class in method, loop or any block between two parentheses. Anonymous class is a class in an expression or a statement. Anonymous classes are used when it has to be used only once and to override the methods. It does not have any class name so it is declared and instantiated in only one statement.

Anonymous classes don't have constructors and have same restrictions as in local classes -

  • The anonymous class can not be accessed from anywhere out from the current block, as it doesn't have any class name.
  • The anonymous classes can access the variables of the enclosing block, but can not change the value of the variables. The anonymous class treats all the variables in the enclosing block as final.
  • The anonymous classes can not have static variables.
  • The variables to be accessed by anonymous class are effectively final. It doesn't matter if the variable declared final or not, if it is to be accessed by the anonymous class, it has to be final. Even, the value of the variable can not be changed after the anonymous class statement anywhere.
Anonymous class is a statement, so its declaration is followed by a semi-colon (;) and also doesn't have any constructor as it doesn't have its own name. Anonymous class can override the methods and can also have its own methods, but its non-overridden methods can not be accessed by anywhere outside from the anonymous class.
public class Simple {
void printText() {
System.out.println("This is a simple text!!");
}
}
Above class is the normal class and have one method to print the simple text.
public class TestAnonymous {
public static void main(String[] args) {
System.out.println("We are in main class");
int finalInt = 10;
// Accessed from anonymous class so can not be changed
//finalInt++;
Simple s = new Simple(); // Used as normal class
s.printText();
Simple as = new Simple() { // Used as anonymous class
void printText() {
System.out.println("This is text from anonymous class!!");
anotherMethod();
}

void anotherMethod() {
System.out.println("Final Value : " + finalInt);
System.out.println("Another Method from anonymous class!!");
}
};
as.printText();
// Can not access non-overridden methods from the anonymous class
// as.anotherMethod();

// Accessed from anonymous class so can not be changed
// finalInt++;
}
}
In above class, the class Simple is used in two ways - (1) Create instance of class Simple and (2) Create instance of anonymous class overriding the method from class Simple.
// Accessed from anonymous class so can not be changed
//finalInt++;
// Accessed from anonymous class so can not be changed
// finalInt++;
Above commented statements show that the variables accessed from the anonymous class is treated as final.
// Can not access non-overridden methods from the anonymous class
// as.anotherMethod();
And above statement shows that anonymous class can have more methods which are not overridden, but can not be accessed. Only methods from the class used to declare, can be accessed.

Here is the output:

We are in main class
This is a simple text!!
This is text from anonymous class!!
Final Value : 10
Another Method from anonymous class!!

The code can be accessed here at Github link.

Thursday, August 6, 2020

Java: Local Classes

We already know about inner class which is declared in another class and is accessed through outer class only. A local class is a class in a method, loop or block. And the local class can not be accessed outside from the method or the block where the class is declared. Local class is only visible to the method or block where it is declared. It is hidden from rest of the program.

When there is need to create a class which should not be reused and should be inaccessible to rest of the world, should be declared as a local class. Like in program below, I have a method rollDice(). rollDice() method has declared a local class Dice, which generates a random number between 1 and 6. Two instances of Dice class created and their numbers are added. Depending on the result, the text is printed. This is the simplest case, we can add more complex instructions. 
import java.util.Scanner;

public class DiceGame {
public static void main(String[] args) {
System.out.println("Mystery number should be between 2 and 12");
System.out.println("Guess the mystery number");
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
rollDice(number);
}

static void rollDice(int number) {
int tempNumber1;
tempNumber1 = 9;
//tempNumber1 = tempNumber1 + 3;
int tempNumber2 = tempNumber1 + 3;

class Dice {
int rand = 0;
int totDice = 0;
int mysteryNumber = 0;
int range = 6;

// Dice constructor
Dice() {
totDice++;
}

// Gets Random Number, if 0 then again gets the random number
void getRandomNumber() {
do {
rand = (int) (range * Math.random());
} while(rand == 0);
}

// Adds Dice number to another Dice number
void addDice(Dice d) {
mysteryNumber = rand + d.rand;
}

// Gets Random Value
int getRandValue() {
return rand;
}

// Checks if Mystery number equals to guessed number
void checkMysteryNumber() {
if(number >= 2 && number <= 12) {
int closeDiff = mysteryNumber - number;
if (mysteryNumber == number) {
System.out.println("Correct!!");
} else if ((closeDiff <= 3) && (closeDiff >= -3)) {
System.out.println("Close Enough!!");
} else if ((closeDiff > 3) || (closeDiff < -3)) {
System.out.println("Good try but not so close!!");
}
System.out.println("Mystery number is : " + mysteryNumber);
} else {
System.out.println("Wrong number!!");
}

}

void finalData() {
// Variables and parameters can be accessed but can't be changed
// tempNumber1++;
// number++;
System.out.println("Temporary Number 1 : - " + tempNumber1);
System.out.println("Parameter number - " + number);
}
}

Dice d1 = new Dice();
Dice d2 = new Dice();
d1.getRandomNumber();
d2.getRandomNumber();
d1.addDice(d2);
d1.checkMysteryNumber();

// Variables and parameters can't be changed in method itself -
// they are effectively final as they are accessed in the local class
// tempNumber1++;
// number++;
System.out.println("");
System.out.println("Final Data Accessed in class");
d1.finalData();
// tempNumber2 is not final as it is not accessed by the local class
tempNumber2 = tempNumber2 + 5;
System.out.println("Data Not Accessed in class, so it's not final");
System.out.println("Temporary Number 2 - " + tempNumber2);
}
}
And the output is:

Mystery number should be between 2 and 12
Guess the mystery number
9
Close Enough!!
Mystery number is : 8

Final Data Accessed in class
Temporary Number 1 : - 9
Parameter number - 9
Data Not Accessed in class, so it's not final
Temporary Number 2 - 17

Local class is a hidden class and can not be accessed from outside, so it has few restrictions - 
  • The local classes can access the parameters passed to the enclosing method but can not change the value of the parameters. The local class treats parameters to the enclosing method as final. 
  • The local classes can access the variables of the enclosing method, but can not change the value of the variables. The local class treats all the variables in the enclosing method as final.
  • Local / Inner classes can not have static variables.
  • The variables and parameters to be accessed by local class are effectively final. It doesn't matter if the variable declared final or not, if it is to be accessed by the local class, it has to be final. Even, the value of the variable can not be changed in the method itself outside the local class.
Above program asks the user to guess the mystery number. And then calls the method rollDice() with the number entered by the user as parameter. In method, a class named Dice is declared. Two instances of class Dice are created. Two numbers are randomly generated. The numbers are added and compared with the guessed number and prints the appropriate message.

In above example, pay close attention to comments -
//tempNumber1 = tempNumber1 + 3;
Above statement will give a compilation error as tempNumber1 is effectively final as it is accessed in the local class.
void finalData() {
// Variables and parameters can be accessed but can't be changed
// tempNumber1++;
// number++;
System.out.println("Temporary Number 1 : - " + tempNumber1);
System.out.println("Parameter number - " + number);
}
Above method is accessing variable declared in method and parameter passed to the method. They can't be changed as they are accessed by the local class.
// Variables and parameters can't be changed in method itself -
// they are effectively final as they are accessed in the local class
// tempNumber1++;
// number++;
System.out.println("");
System.out.println("Final Data Accessed in class");
d1.finalData();
Above statements are written after local class declaration and using class methods. Still, the program can't change the variable and parameter as they are still treated like final.
// tempNumber2 is not final as it is not accessed by the local class
tempNumber2 = tempNumber2 + 5;
System.out.println("Data Not Accessed in class, so it's not final");
System.out.println("Temporary Number 2 - " + tempNumber2);
But above statement is perfectly fine as the variable tempNumber2 is not accessed by local class.

The code can be accessed here at Github Link.