The Programming View
Blog about Java, C, C++ programming language & more about ICT knowledge !!!
Search This Blog
Saturday 23 April 2016
Thursday 21 April 2016
Wednesday 27 May 2015
2048 code in JAVA without GUI
/* I have made 4 different classes as per my requirements.Here Blank square boxes defined as 0's.
* I would suggest you to run this by copying individual class in Eclipse-IDE. Open Eclipse then
* define a package game and then make classes as given in Source Code.For Any query comment
* or message me on g+.
*
*author @ Maulik Gohil.
*
*/
/* Class Main*/
package game;
import java.util.Random;
public class Main {
public static int[][] a=new int[][]{{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
public static void main(String args[])
{
Show show=new Show();
boolean flag=true;
while(flag)
{
show.doPrintArray(a);
}
}
}
/*Class Show*/
package game;
import java.util.Random;
import java.util.Scanner;
public class Show {
Scanner scr=new Scanner(System.in);
public void doPrintArray(int[][] a) {
int count=0;
Random randomNum=new Random();
String s="22242224222";
char num= s.charAt(randomNum.nextInt(s.length()));
String numString=String.valueOf(num);
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j]==0)
count++;
String[] storeFreeBlocks=new String[count];
int localcounter=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(a[i][j]==0)
{
storeFreeBlocks[localcounter]=String.valueOf(i)+","+String.valueOf(j);
localcounter++;
}
}
}
String getFreeBlock=storeFreeBlocks[randomNum.nextInt(storeFreeBlocks.length)];
String[] getRowCol=getFreeBlock.split(",");
int p=Integer.parseInt(getRowCol[0]);
int q=Integer.parseInt(getRowCol[1]);
a[p][q]=Integer.parseInt(numString);
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(a[i][j]==16)
{
System.out.println("you won");
System.exit(0);
}
}
}
int choice=Integer.parseInt(scr.nextLine());
Process ps=new Process(choice,a);
}
}
/*Class Process*/
/* Class GetSet*/
package game;
public class GetSet {
public int getDown(int[][] a,int i,int j) {
if(i<3)
return a[i+1][j];
else
return 1;
}
public int getUp(int[][] a,int i,int j) {
if(i>0)
return a[i-1][j];
else
return 1;
}
public int getLeft(int[][] a,int i,int j) {
if(j>0)
return a[i][j-1];
else
return 1;
}
public int getRight(int[][] a,int i,int j) {
if(j<3)
return a[i][j+1];
else
return 1;
}
}
* I would suggest you to run this by copying individual class in Eclipse-IDE. Open Eclipse then
* define a package game and then make classes as given in Source Code.For Any query comment
* or message me on g+.
*
*author @ Maulik Gohil.
*
*/
/* Class Main*/
package game;
import java.util.Random;
public class Main {
public static int[][] a=new int[][]{{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};
public static void main(String args[])
{
Show show=new Show();
boolean flag=true;
while(flag)
{
show.doPrintArray(a);
}
}
}
/*Class Show*/
package game;
import java.util.Random;
import java.util.Scanner;
public class Show {
Scanner scr=new Scanner(System.in);
public void doPrintArray(int[][] a) {
int count=0;
Random randomNum=new Random();
String s="22242224222";
char num= s.charAt(randomNum.nextInt(s.length()));
String numString=String.valueOf(num);
for(int i=0;i<4;i++)
for(int j=0;j<4;j++)
if(a[i][j]==0)
count++;
String[] storeFreeBlocks=new String[count];
int localcounter=0;
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(a[i][j]==0)
{
storeFreeBlocks[localcounter]=String.valueOf(i)+","+String.valueOf(j);
localcounter++;
}
}
}
String getFreeBlock=storeFreeBlocks[randomNum.nextInt(storeFreeBlocks.length)];
String[] getRowCol=getFreeBlock.split(",");
int p=Integer.parseInt(getRowCol[0]);
int q=Integer.parseInt(getRowCol[1]);
a[p][q]=Integer.parseInt(numString);
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
for(int i=0;i<4;i++)
{
for(int j=0;j<4;j++)
{
if(a[i][j]==16)
{
System.out.println("you won");
System.exit(0);
}
}
}
int choice=Integer.parseInt(scr.nextLine());
Process ps=new Process(choice,a);
}
}
/*Class Process*/
package game;
public class Process {
int move;
Process(int choice, int[][] a) {
move=choice;
GetSet gs=new GetSet();
switch(move)
{
case 2:
for(int j=0;j<4;j++)
{
for(int i=3;i>=0;i--)
{
if(a[i][j]!=0)
{
int tempi=i;
while(gs.getDown(a, tempi, j)==0)
{
tempi++;
}
if(gs.getDown(a, tempi, j)!=0 && gs.getDown(a, tempi, j)==a[i][j])
{
a[tempi+1][j]+=a[i][j];
a[i][j]=0;
}
if(tempi!=i)
{
a[tempi][j]=a[i][j];
a[i][j]=0;
}
}
}
}
//app.setArray(a);
break;
case 8:
for(int j=0;j<4;j++)
{
for(int i=0;i<=3;i++)
{
if(a[i][j]!=0)
{
int tempi=i;
while(gs.getUp(a, tempi, j)==0)
{
tempi--;
}
if(gs.getUp(a, tempi, j)!=0 && gs.getUp(a, tempi, j)==a[i][j])
{
a[tempi-1][j]+=a[i][j];
a[i][j]=0;
}
if(tempi!=i)
{
a[tempi][j]=a[i][j];
a[i][j]=0;
}
}
}
}
//app.setArray(a);
break;
case 4:
for(int i=0;i<4;i++)
{
for(int j=0;j<=3;j++)
{
if(a[i][j]!=0)
{
int tempj=j;
while(gs.getLeft(a, i, tempj)==0)
{
tempj--;
}
if(gs.getLeft(a, i, tempj)!=0 && gs.getLeft(a, i, tempj)==a[i][j])
{
a[i][tempj-1]+=a[i][j];
a[i][j]=0;
}
if(tempj!=j)
{
a[i][tempj]=a[i][j];
a[i][j]=0;
}
}
}
}
//app.setArray(a);
break;
case 6:
for(int i=0;i<4;i++)
{
for(int j=3;j>=0;j--)
{
if(a[i][j]!=0)
{
int tempj=j;
while(gs.getRight(a, i, tempj)==0)
{
tempj++;
}
if(gs.getRight(a, i, tempj)!=0 && gs.getRight(a, i, tempj)==a[i][j])
{
a[i][tempj+1]+=a[i][j];
a[i][j]=0;
}
if(tempj!=j)
{
a[i][tempj]=a[i][j];
a[i][j]=0;
}
}
}
}
//app.setArray(a);
break;
default:
System.out.println("Invalid Entry");
}
}
}
/* Class GetSet*/
package game;
public class GetSet {
public int getDown(int[][] a,int i,int j) {
if(i<3)
return a[i+1][j];
else
return 1;
}
public int getUp(int[][] a,int i,int j) {
if(i>0)
return a[i-1][j];
else
return 1;
}
public int getLeft(int[][] a,int i,int j) {
if(j>0)
return a[i][j-1];
else
return 1;
}
public int getRight(int[][] a,int i,int j) {
if(j<3)
return a[i][j+1];
else
return 1;
}
}
Sunday 3 May 2015
10 Things about Strings in JAVA
String in Java is very special class and most frequently used class as
well. There are lot many things to learn about String in Java
than any other class, and having a good knowledge of different String
functionalities makes you to use it properly. Given heavy use of Java String in almost
any kind of project, it become even more important to know subtle detail about
String. Though I have shared lot of String related article already here in
Javarevisited, this is an effort to bring some of String feature together. In
this tutorial we will see some important points about Java String, which is
worth remembering. You can also refer my earlier post 10
advanced Java String questions to know more about String. Though I
tried to cover lot of things, there are definitely few things, which I might
have missed; please let me know if you have any question or doubt on java.lang.String
functionality and I will try to address them here.
1)
Strings are not null terminated in Java.
Unlike C and C++, String in Java doesn't terminate with null character. Instead
String are Object in Java and backed by character array. You can get the
character array used to represent String in Java by calling toCharArray() method of java.lang.String class of
JDK.
2)
Strings are immutable and final in Java
Strings are immutable in Java it means once created you cannot modify
content of String. If you modify it by using toLowerCase(), toUpperCase() or any
other method, It always result in new
String. Since String is final there is no way anyone can extend String or
override any of String functionality. Now if you are puzzled why
String is immutable or final in Java. checkout the link.
3)
Strings are maintained in String Pool
As I Said earlier String is special class in Java and all String literal
e.g. "abc" (anything
which is inside double quotes are String literal in Java) are maintained in a
separate String pool, special memory location inside Java memory, more
precisely inside PermGen
Space. Any time you create a new String object using String literal, JVM
first checks String pool and if an object with similar content available, than
it returns that and doesn't create a new object. JVM doesn't perform String
pool check if you create object using new operator.
You may face subtle issues if you are not aware of this String behaviour , here is an example
String name = "Scala"; //1st String object
String name_1 = "Scala"; //same object referenced by name variable
String name_2 = new String("Scala") //different String object
//this will return true
if(name==name_1){
System.out.println("both name and name_1 is pointing to same string object");
}
//this will return false
if(name==name_2){
System.out.println("both name and name_2 is pointing to same string object");
}
if you compare name and name_1 using equality operator "==" it will
return true because both are pointing to same object. While name==name_2 will
return false because they are pointing to different string object. It's worth
remembering that equality
"==" operator compares
object memory location and not characters of String. By default Java puts
all string literal into string pool, but you can also put any string into pool
by calling intern() method of java.lang.String class,
like string created using new() operator.
4) Use
Equals methods for comparing String in Java
String class overrides equals method and provides a content equality,
which is based on characters, case and order. So if you want to compare two
String object, to check whether they are same or not, always use equals() method
instead of equality operator. Like in earlier example if we use equals
method to compare objects, they will be equal to each other because they
all contains same contents. Here is example of comparing String using equals
method.
String name = "Java"; //1st String object
String name_1 = "Java"; //same object referenced by name variable
String name_2 = new String("Java") //different String object
if(name.equals(name_1)){
System.out.println("name and name_1 are equal String by equals method");
}
//this will return false
if(name==name_2){
System.out.println("name_1 and name_2 are equal String by equals method");
}
You can also check my earlier post difference
between equals() method and == operator for more detail discussion on
consequences of comparing two string using == operator in Java.
5) Use
indexOf() and lastIndexOf() or matches(String regex) method to search inside
String
String class in Java provides
convenient method to see if a character or sub-string or a pattern
exists in current String object. You can use indexOf() which will
return position of character or String, if that exist in current String object
or -1 if character doesn't exists in String. lastIndexOf is similar
but it searches from end. String.match(String regex) is even
more powerful, which allows you to search for a regular
expression pattern inside String. here is examples of indexOf, lastIndexOf and matches method
from java.lang.String class.
String str = "Java is best programming language";
if(str.indexOf("Java") != -1){
System.out.println("String
contains Java at index :" + str.indexOf("Java"));
}
if(str.matches("J.*")){
System.out.println("String
Starts with J");
}
str ="Do you like Java ME or Java EE";
if(str.lastIndexOf("Java") != -1){
System.out.println("String contains Java lastly at: " + str.lastIndexOf("Java"));
}
As expected indexOf will return 0 because characters
in String are indexed from zero. lastIndexOf returns
index of second “Java”, which starts at 23 and matches
will return true because J.* pattern is any String starting with character
J followed by any character because of dot(.) and any
number of time due to asterick (*).
Remember matches() is tricky and some time
non-intuitive. If you just put "Java" in matches
it will return false because String is not equals to
"Java" i.e. in case of plain text it behaves like equals method. See here
for more examples of String matches() method.
Apart from indexOf(), lastIndexOf() and matches(String
regex) String also has methods like startsWith() and endsWidth(), which can
be used to check an String if it starting or ending with certain character or
String.
6) Use
SubString to get part of String in Java
Java String provides another useful method called substring(), which can
be used to get parts of String. basically you specify start and end index and substring() method
returns character from that range. Index starts from 0 and goes till String.length()-1. By the
way String.length() returns you number of characters in String,
including white spaces like tab, space. One point which is worth remembering
here is that substring is also backed up by character array, which is used by
original String. This can be dangerous if original string object is very large
and substring is very small, because even a small fraction can hold reference
of complete array and prevents it from being garbage collected even if there is
no other reference for that particular String. Read How
Substring works in Java for more details. Here is an example of using SubString
in Java:
String str = "Java is best programming language";
//this will return part of
String str from index 0 to 12
String subString = str.substring(0,12);
System.out.println("Substring: " + subString);
7)
"+" is overloaded for String concatenation
Java
doesn't support Operator overloading but String is special and + operator
can be used to concatenate two Strings. It can even used to convert int, char, long or double to convert
into String by simply concatenating with empty
string "". internally + is implemented
using StringBuffer prior to Java 5 and StringBuilder from Java
5 onwards. This also brings point of using StringBuffer or StringBuilder for
manipulating String. Since both represent mutable object they can be used to
reduce string garbage created because of temporary String. Read more about StringBuffer
vs StringBuilder here.
8) Use
trim() to remove white spaces from String
String in Java provides trim() method to remove white space
from both end of String. If trim() removes white spaces it
returns a new String otherwise it returns same String. Along with trim() String also provides replace() and replaceAll() method for
replacing characters from String. replaceAll method even
support regular expression. Read more about How to replace String in Java here.
9) Use
split() for splitting String using Regular expression
String in Java is feature rich. it has methods like split(regex) which can
take any String in form of regular expression and split the String based on
that. particularly useful if you dealing with comma separated file (CSV) and
wanted to have individual part in a String array. There are other methods also
available related to splitting String, see this Java
tutorial to split string for more details.
10) Don't
store sensitive data in String
String pose security threat if used for storing sensitive data like
passwords, SSN or any other sensitive information. Since String is immutable in
Java there is no way you can erase contents of String and since they are kept
in String pool (in case of String literal) they stay longer on Java heap ,which
exposes risk of being seen by anyone who has access to Java memory, like
reading from memory dump. Instead char[] should be
used to store password or sensitive information. See Why
char[] is more secure than String for storing passwords in Java for more
details.
11) Character Encoding and String Apart from all these 10 facts about String in Java, the most critical thing to know is what encoding your String is using. It does not make sense to have a String without knowing what encoding it uses. There is no way to interpret an String if you don't know the encoding it used. You can not assume that "plain" text is ASCII. If you have a String, in memory or stored in file, you must know what encoding it is in, or you cannot display it correctly. By default Java uses platform encoding i.e. character encoding of your server, and believe me this can cause huge trouble if you are handling Unicode data, especially if you are converting byte array to XML String. I have faced instances where our program fail to interpret Strings from European language e.g. German, French etc. because our server was not using Unicode encodings like UTF-8 or UTF-16. Thankfully, Java allows you to specify default character encoding for your application using system property file.encoding. See here to read more about character encoding in Java
11) Character Encoding and String Apart from all these 10 facts about String in Java, the most critical thing to know is what encoding your String is using. It does not make sense to have a String without knowing what encoding it uses. There is no way to interpret an String if you don't know the encoding it used. You can not assume that "plain" text is ASCII. If you have a String, in memory or stored in file, you must know what encoding it is in, or you cannot display it correctly. By default Java uses platform encoding i.e. character encoding of your server, and believe me this can cause huge trouble if you are handling Unicode data, especially if you are converting byte array to XML String. I have faced instances where our program fail to interpret Strings from European language e.g. German, French etc. because our server was not using Unicode encodings like UTF-8 or UTF-16. Thankfully, Java allows you to specify default character encoding for your application using system property file.encoding. See here to read more about character encoding in Java
That's all about String in Java. As I have said String is very special in
Java, sometime even refer has God class. It has some unique feature like immutability, concatenation
support, caching etc, and to become a serious Java programmer,
detailed knowledge of String is quite important. Last but not the least don't
forget about character
encoding while converting a byte array into String in Java. Good knowledge of java.lang.String is must for good Java developers.
Monday 20 April 2015
10 Great Intel Galileo Features
Intel and Arduino’s announcement about the new Galileo board is big news. It’s a Linux-based board that I’ve found to be remarkably compatible with the Arduino ecosystem based on my first few steps with a prerelease version of the board. Here are some of the best features of this groundbreaking collaboration between Intel and Arduino:
Shield Compatibility
The expansion header on the top of Galileo should look familiar since it’s compatible with 5V and 3.3V Arduino shields designed for the Uno R3 (also known as the Arduino 1.0 pinout). This means that it has 14 digital I/O pins, 6 analog inputs, a serial port, and an ICSP header.
Familiar IDE
The Intel-provided integrated development environment for the Galileo looks exactly like the Arduino IDE on the surface. Under the Boards menu, you’ll see addition of the Galileo under “Arduino X86 Boards.” The modified IDE also is capable of upgrading the firmware on the board.
Ethernet Library Compatibility
Using the Ethernet port on the board is as simple as using Arduino’s Ethernet library. I was able to get a HTTP connection to Google without even modifying the standard WebClient example.
Real Time Clock
Most Linux boards rely on a connection to the Internet to get the current date and time. But with Galileo’s on-board RTC (real time clock), you’ll be able to track time even when the board is powered off. Just wire up a 3.0V coin cell battery to the board.
Works with PCI Express Mini Cards
On the bottom of the board is an expansion slot for PCI Express Mini cards. This means you can connect WiFi, Bluetooth, GSM cards for connectivity, or even a solid state drive for more storage. When you connect a WiFi card, it will work with Arduino’s Wifi library.
USB Host Port
Galileo’s dedicated USB On-The-Go port will let you use the the Arduino USB Host library to act as a keyboard or mouse for other computers.
MicroSD Support
If you want to store data, a microSD card slot is accessible from your code by using the standard Arduino SD card library.
TWI/I2C, SPI Support
Using the standard Arduino Wire library or SPI library, you can connect TWI/I2C or SPI components to the Galileo.
Serial Connectivity
Not only is there the typical serial port for your sketches on pins 0 and 1 of the Arduino pinout, but there’s also a separate serial port for connecting to the Linux command line from your computer. You’ll connect to it through the audio jack interconnect next to the Ethernet port. This port is only used for serial.
Linux on Board
A very light distribution of Linux is loaded onto the 8 MB of flash memory. If you want to use tools like ALSA (for sound), V4L2 (for video input), Python, SSH, node.js (for web projects), and openCV (for computer vision), you can boot Galileo from an SD card image that Intel provides
Wednesday 15 April 2015
Tuesday 14 April 2015
3 Ways to Prevent Method Overriding in Java - Private, Static and Final
Every Java programmer knows that final modifier can be used to prevent method overriding in Java because there is no way someone can override final methods; but, apart from final modifier, is there any other way to prevent method overriding in Java? This was the exact question, asked to one of my friend in a recent Java interview at one of the leading Investment bank. I guess, he was lucky to get this question because he already knows those tricks and was able to answer it quickly. When he told me about his experience, I didn't understand why someone ask this question? What is the purpose? What they were trying to find out? I can understand if they have asked what's the best way to prevent method overriding in Java, or what is the risk of overriding? Anyway, It gives me an opportunity to recap some of the other technique (syntactically) to prevent a method from being overridden and write this blog post to share some mystery tricks from Java world. Some of you might be aware of those non obvious way to prevent method overriding, but if you don't, here is your opportunity to learn.
In terms of performance, I think all three private, static and final method performs more or less same, because they all bonded during compile time using static binding. Another reason of using final modifier to prevent method overriding is compile time check. Since an attempt to override a final method is a compilation error in Java, it prevents accidental overriding. On the other handprivate and static methods can unknowingly hide super class method and create subtle bugs, because compiler will not flag any error or warning. By the way, you can avoid this kind of accidental method overriding by using @Override annotation in Java. If you use @Override annotation, whenever you intent to override a method, compiler will flag error and save you from accidentally hidingprivate and static methods. Just try following Java program after putting @Override annotation on static and private method, to see how compiler helps you.
In the code above, you can see that in Base.java we have three methods, final method version(), static method name() and private method where(). In the sub class Derived.java, we tried to override final method but compiler gave us error, forcing us to comment that code. Though we are able to create private and static method of same name and syntax in the sub class, but this is not overriding. To verify that we ran the program and program called methods of derived object with type of base class. In this case any overridden method will be execute code defined in derive class but you can see from output that code defined in Base class is executed. In short, its not possible to override private and static method in Java.
That's all about 3 ways to prevent a method from being overridden in Java. Remember, though syntactically you can use private, static and final modifier to prevent method overriding, but you should always use final modifier to prevent overriding. final is best way to say a method is complete and can't be overridden. It's also a good coding practice in Java to use @Override annotation, when your intention is overriding and not hiding, this will prevent subtle bugs. You should also be clear, when to use final keyword in Java, because it limits client's ability to override something, but same time necessary to prevent security and sensitive behavior intact.
Private, Static and Final Methods - Can't Overridden in Java
Apart from final methods there are two more techniques which you can use to prevent a method from being overridden in Java. If you are familiar with private and static modifier in Java, then you may be knowing that private method is not accessible in subclass, which means they can not be overridden as well, because overriding happens at child class. Similarly, static methods can not be overridden in Java, because they are resolved and bonded during compile time, while overriding takes place at runtime. They are resolved based upon the type and not object. Overriding happens due to polymorphic property of objects. By the way, can you override static methods in Java and why a static method can not be overridden in Java, are also two of the most frequently asked Java questions. In short, apart from final modifier, you can also use static and private modifier to prevent a method from being overridden.Best Way to Prevent Method Overriding in Java
As far as Java best practice is concern, you should always use final keyword to indicate that a method is not meant for overriding. final modifier has a readability advantage, as well as consistency advantage, because as soon as a Java programmer sees a final method, he knows that this can not be overridden. Private method implies that this method is only accessible in this class, which in turns implies that, you can not override private methods on derived class. As you can see, private methods still requires one more step to realize that it can not be overridden. What creates confusion with private and static methods are that, you can hide these methods in subclass. There is a difference between method hiding and method overriding, A method is hidden in subclass, if it signature is same as of super class method, but at a call to hidden method is resolved during compile time, while a call to overridden method is resolved during run time.In terms of performance, I think all three private, static and final method performs more or less same, because they all bonded during compile time using static binding. Another reason of using final modifier to prevent method overriding is compile time check. Since an attempt to override a final method is a compilation error in Java, it prevents accidental overriding. On the other handprivate and static methods can unknowingly hide super class method and create subtle bugs, because compiler will not flag any error or warning. By the way, you can avoid this kind of accidental method overriding by using @Override annotation in Java. If you use @Override annotation, whenever you intent to override a method, compiler will flag error and save you from accidentally hidingprivate and static methods. Just try following Java program after putting @Override annotation on static and private method, to see how compiler helps you.
Code Example - Private, Static and Final method
In this Java program, we will create two classes Base and Derived with three methods, one static, one final and one private. By observing output, you can see verify that final, private and static methods can not be overridden in Java. Since overriding final methods is compilation error, I had to comment that code. You can clearly see that, even though we have similar private and static methodin Derived class, and we are using Derived object to call those method, they are not called. Which means private and static method can only be hidden, but not overridden.package test; /** * Java program to show that private, static and final method can not be * overridden in Java. */ public class PrivateFinalStaticOverridingTest { public static void main(String args[]) { // Reference variable of type Base - Object of type Derived Base b = new Derived(); System.out.println(b.version()); System.out.println(b.name()); } } /** * Base Class which contains three methods with final, static, and private * modifier, to show that these method can't be overridden in Java. * * @author Javin */ class Base{ public final String version(){ where(); // This will call Base class where() method return "1.0.0"; } public static String name(){ return "Base"; } private void where(){ System.out.println("Inside Base Class"); } } /** * Derived Class, which extends Base and tries to override final, static * and private methods in Java. */ class Derived extends Base{ // Compilation Error : Final method can't be overridden in Java // public final String version(){ // return "2.0.0"; // } // Hidden static method - Same Signature but bonded at compile time public static String name(){ return "Derived"; } // Hidden private method - Same signature but resolved at compile time private void where(){ System.out.println("Inside Derived Class"); } } Output: Inside Base Class 1.0.0 Base
In the code above, you can see that in Base.java we have three methods, final method version(), static method name() and private method where(). In the sub class Derived.java, we tried to override final method but compiler gave us error, forcing us to comment that code. Though we are able to create private and static method of same name and syntax in the sub class, but this is not overriding. To verify that we ran the program and program called methods of derived object with type of base class. In this case any overridden method will be execute code defined in derive class but you can see from output that code defined in Base class is executed. In short, its not possible to override private and static method in Java.
That's all about 3 ways to prevent a method from being overridden in Java. Remember, though syntactically you can use private, static and final modifier to prevent method overriding, but you should always use final modifier to prevent overriding. final is best way to say a method is complete and can't be overridden. It's also a good coding practice in Java to use @Override annotation, when your intention is overriding and not hiding, this will prevent subtle bugs. You should also be clear, when to use final keyword in Java, because it limits client's ability to override something, but same time necessary to prevent security and sensitive behavior intact.
Subscribe to:
Posts (Atom)