Total Pageviews

Friday, February 18, 2011

Abstract Class

Abstract Class in java
Abstract classes can be implemented in java. A class is declared abstract using the keyword "abstract" as a prefix. An abstract class may or may not contain any
abstract method. Now lets understand what exactly is an abstract class. Abstract class can be considered as a generic class implemented. Consider the following example :
Their are diffrent classes for various shapes like Rectangle,Square,Circle,Ellipse....
All share some comman properties like color,dimension,fillColor. These comman features/functionality can be kept in a generic class called Shapes. Also each individual class differs in size. Lets say each needs a method changeSize(), The method cannot be kept in superclass Shapes as each class has its own implementation and Shapes being a generic class does not requires this function. If we declare this function as abstract, its signature can be kept in the Shapes class. Each class which extends the Shapes class can write the changeSize method as per its own implementation.

Note that the same can be achieved using interfaces also, but interface cannot have implemenaion of the methods. So the comman methods would be required to be defined in all the classes implementing the interface. Interfaces will be discussed later in the blog,but for the time being just consider it as an implementaion of inheritance in java.

Some key points in abstract classes:
1.A subclass extending an abstract class may or may not define the abstract methods. To do so make the subclass itself as abstract.
2. Abstract class cannot be instantiated.
3. If implementation contains only method signatures and those methods need to be overridden in every sub class then make it as interface rather than abstract class.


An advantage of abstract class over interace is that abstract classes can contain concrete methods also. So in guture if a new method is to be introduced, just add it as a concrete method in abstract class and can be used by the subclass.

Abstract class example:


abstract class Shapes{
private String color; // Should have used Color class instead
public void setColor(String color){
.....
}
public void abstract changeShape(....); //No implementation
}

public class Rectangle extends Shapes{

public void changeShape(...){
//implement the specialises method
}
}


It can also be possible for a class not implementing all the abstract methods. Add another abstract method named "repostion" in Shapes class.
Now do as followed


abstract class Rectangle extends Shapes{
public void changeShape(...){
//implement the specialises method
}
}


class AnotherClass extends Rectangle {

public void reposition(){
//implemet method here
}
}

The above class contaiins all the abstract methods of the Shapes class which were not implemented by Rectangle class.

For more details on abstract class click here .
For comparison between abstract class and interface click here

Thursday, February 17, 2011

Inheritance Continued....

Lets look deeply into inheritance.
Consider the following example :
public class SuperClass{
public String name = "SuperClass Name";
public static String staticName = " SuperClass Static Name";
public static String staticString = "SuperClass Staic String";

public static void printVal(){
.............
}
public void checkVal(){
........
}
}

public class SubClass extends SuperClass{
public String name = "SubClass name";
public static String staticName = "SubClass static name";
protected int staticString = 1;


public static void printVal(){
.............
}
public void checkVal(){
........
}
}

public static void main(....){
SuperClass superWithSuperCon = new SuperClass();
SuperClass superWithSubCon= new SubClass();
SubClass subWithSubCon = new SubClass();

sout(superWithSuperCon.name);
sout(superWithSuperCon.staticName); /*Though being static should have been accessed by using Class name,but java converts the same automatically at compile time(Not recommended)*/
sout(superWithSuperCon..staticString);

sout(superWithSubCon.name);
sout(superWithSubCon.staticName);
sout(superWithSubCon.staticString);

sout(subWithSubCon.name);
sout(subWithSubCon.staticName);
sout(subWithSubCon.staticString);

superWithSuperCon.printVal(); /*SuperClass methods called - Compile time binding*/
superWithSuperCon.checkVal(); /*SuperClass methods called - Run time binding*/

superWithSubCon.printVal(); /*SuperClass methods called - Compile time binding*/
superWithSubCon.checkVal(); /*SubClass methods called - Run time binding*/

subWithSubCon.printVal(); /*SubClass methods called - Run time binding*/
subWithSubCon.checkVal(); /*SubClass methods called - Run time binding*/
}
The output obtained is :
SuperClass Name
SuperClass Static Name
SuperClass Staic String
SuperClass Name
SuperClass Static Name
SuperClass Staic String
SubClass name
SubClass static name
1
The strange behaviour of variable in case 4 is because java does not supports instance variable overriding.Since static variables are class variables they are resolved during compile time only.
Note : Methods of type private/final/static or constructors are resolved at compile time only ie static binding.

Thursday, February 3, 2011

Files with no public classes can have a name that does not match any of the classes in the file.


if you declare a class A in a file called X.java as follows ::

class A{

------

}


the class will compile correctly.

But if you declare the class A as ::

public class A{

}

this will result in an error as --- ( class A is public, must be declared in a file A.java )



This comes under Source File Declaration Rules as defined by java Developers.






Sunday, January 30, 2011

Static Method are always resolved during Compile Time


Consider the following snippet of code :


class SuperClass{

public static void staticMethod(){

System.out.println("SuperClass: inside staticMethod");

}

}


public class SubClass extends SuperClass{

public static void staticMethod(){

System.out.println("SubClass: inside staticMethod");

}


public static void main(String []args){

SuperClass superClassWithSuperCons = new SuperClass();

SuperClass superClassWithSubCons = new SubClass();

SubClass subClassWithSubCons = new SubClass();


superClassWithSuperCons.staticMethod();

superClassWithSubCons.staticMethod();

subClassWithSubCons.staticMethod();

}


}






It will be interesting to note that the output will be


SuperClass: inside staticMethod

SuperClass: inside staticMethod

SubClass: inside staticMethod



Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods). Okay... Because they are class methods and hence access to them is always resolved during compile time only using the compile time type information.


we're invoking the staticMethod() on an object of Runtime Type as SubClass and not as SuperClass. This confirms that the static methods are always resolved using their compile time type information only Since at compile time first two of the objects contains references to the SuperClass only.





Friday, January 28, 2011

Call by Value vs Call by Reference

We all are familier with two methods of paramter passing - call by value and call by refenence. Now the question arises java supports call by value or call by reference. Lets just for the time being consider few examples and then decide what java follows.

int n = 10;
doubleNumber(n);

Declaration of doubleNumber(...)
public void doubleNumber(int num){ //line 1
num = num * 2; //line 2
}

In the above example when line 1 is encountered,JVM makes a copy of the variable "n". When the control is returend from the function the variable num is no longer in the memory, so originally declared variable "n" remains unchanged in state. Hence by the above example we conclude that java supports call by value.

Now lets try our hands on some objects( Remember int was a primitive type not an object)
Employee emp = new Employee();
raiseSalary(emp);

public void raiseSalary(Employee e){//Line 1
e.setSalary(e.getSalary()*2);
}

Now when the call returns to the caller method surprisingly the value of the salary referred by original object "emp" changes. This happens because at line 1 variable e contains the copy of value at emp ie object refernce. Now both e and emp point to same memory location. So after return object e is collected by the garbage collector but the changes are reflected back . But does that means that java follows pass by reference. Well the answer is NO. Lets understand it with the same Employee class. Take a deep look at the emample below:

Employee emp1 = new Employee();
Employee emp2 = new Employee();

swapEmpObjects(emp1,emp2);

public void swapEmpObjects(Employee obj1,Employee obj2){
Employee temp;
temp = obj1;
obj1 = obj2;
obj2 = temp;
}

Now what happens is obj1 and obj2 contains object reference to emp1 and emp2. After the control returns from the function obj1 and obj2 gets interchanged that is their object reference changes. Since copy of object reference is contained in obj1 and obj2, the objects emp1 and emp2 remains unaltered. In nutshell object referene are passed by value in java. Hence java supports call by value.

Sunday, January 23, 2011

Inheritance and Accessibility


determine which of the print statement has an error if the code is executed
as new B( ).printInfo from main method ---->


class A
{
int x;
private boolean y;
protected String z;
private static int m;
A( )
{
x = 10;
y = true;
z = "mohit";
m++;
}
public int getX( ){return x};
private void getY( ){return y};
public static void incr( )
{
sop( m );
}
}


class B extends A
{
public void printInfo() {
sop( x ); // 1
sop( y); // 2
sop(getX( )); // 3
sop(getY()); // 4
sop(m); // 5
incr();
}

}

Overriding v/s Hiding


Consider the code snippet::


class Foo {
public static void classMethod() {
System.out.println(“classMethod() in Foo”);
}

public void instanceMethod() {
System.out.println(“instanceMethod() in Foo”);
}
}

class Bar extends Foo {
public static void classMethod() {
System.out.println(“classMethod() in Bar”);
}

public void instanceMethod() {
System.out.println(“instanceMethod() in Bar”);
}
}


Let's Consider the following main method to test above code


class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}



If you run this, the output is

instanceMethod() in Bar
classMethod() in Foo


Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That’s how Java normally works for instance methods.


It would be better coding style to write either:

Foo.classMethod();

or

Bar.classMethod();

That way, it is crystal clear which class method you would like to call.





Thursday, January 20, 2011

Static Keyword

Static Keyword

Static keyowrd can be applied to a member function or a member field of a class. Static is one of the most interesting keywords in java. Staticvariables/methods are class variables/methods. By class variables i mean that if 10 instances are created for a class then each object has its own value for the fields other than the static fields. Static fields are comman to all the objects ie if one objects modifies the value,it is reflected in all other objects.
To access a static method/filed always use CLASSNAME.fieldname/methodname. Though the same can be accessed using object name also but this approach is strictly not recommended,as it adds to confusion.


 We declare methods as static when there is no need for an implicit parameter( By imp  licit i mean is the object name ie "this" in java). So methods can be directly called. Static blocks are  initialsed as soon as the class is lodaed.
  They are called before the constructor is created. They remain  in memory even after the constructor is removed.


Try the following code:

public class TestStatic{

static{
sout("hello i am not in main method");
}

public static void main(String [] args){
sout("in main method");
}

Output is
hello i am not in main method
in main method


Ok here are some excercise for you. I request not to run it on system. Just think  over the possible outcome and comment upon the result. Lets discuss what the  output can be and why so. I beleive i can get some active users for discussion :

1.Try out the above example by omiiting the main method and run the program using  command prompt. It yields interesting result.
2. Try creating a static  variable in a static/non static method.
3. Return a static variable(both mutable and immutable) to a non static variable.  Change the value of the non static variable and print the returned variable( using getter method of the class). See whether the value changes or not.
4. Output of the program :
public class LearnJava{
public static void main(String[] args){
 System.out.println("in main");
}

Static{
                System.out.println(" out of  hello");
}

 static{
 System.out.println("hello");
}
}

5. Output of the program :

public class LearnJava{
static{
 System.out.println(" out of  hello");
}
public static void main(String[] args){
 System.out.println("in main");
}

 static{
 System.out.println("hello");
}
}


6. WAP to distibute 8 cards to 1 user from a deck of 52 playing cards.
7. WAP to distribute all 52 cards amongst 4 users by each player picking one card  randomnly at a time.(For simplicity it can be assumed that cards have nymber  form 1 to 52 for both questions) HINT: Create 4 objects of the Cards class.

PS: There is a lot more which can be covered in this article. Please post as much as you can.


Final Keyword

FInal Keyword in java - Final keyword can be used to make a class,method or a
field as final. When used with class it means that the class cannot be used by
a subclass ie no inheritance (like String class). When a method is declared as
final it means that the method cannot be overrided by any subclass. Technically
any method if used by a constructor must be declared as final to disallow it
being over ridden causing data corruption (as method can be over- rided).

There are two meanings when a variable is declared as final. Consider the
following example:
final String str ="amit";

This means that the value of str remains unchanged in the entire program.A good
approach for this is use capital letters for variable name.

final Date date;

The above declaration means that the date object reference is constant ie it
cannot refer to any other object once initialized. But it does not states that
the value of date cannot be changed. We can always use methods of date class to
change the values.Consider the example:
final Date d;
d= new Date();
d.setHours(12);
System.out.println("hours"+d.getHours());
d.setHours(15);
System.out.println("hours"+d.getHours());

The value changes to 15. But if you try to reassign the object d to another
memory location,java gives error as the object is declared final.

Thumb Rule: Use final with primitive or immutable data types. Other objects
declared as final leads to confusion.

Wednesday, January 19, 2011

Encapsulation

Classes - Blueprint of an object.
Object- Real world entity.

Constructors in java are always initialized using a new keyword.
 Employee emp("name","salary"); //C++ style not allowed in java
For java use Employee emp = new Employee("name","salary");
Encapsulation - Wrapping of data in a single unit. We provide some methods to change the data
values. Encapsulation if not properly implemented can lead to drastic results. Consider the 
following example :
public class Employee {

   private String name;
   private Date dob;

    public Employee(String name, Date dob) {
        this.name = name;
        this.dob = dob;
    }

    public Date getDob() {
        return dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
  
}

Now create an object of this class in some other class.
Date date = new Date(); //System's current date...though cannot be the birth date but after
                          all its an example only :D
date.setHours(10); //Changed one of the values of time to show the output
String name = "amit";
Employee emp = new Employee(name,date);
Now save  the values in objects using getter methods
Date d1 = emp.getDob();
String nameStr = emp.getname();
sout("dob "+ d1.getHours() + " name " + nameStr);//from now onwards all examples will use 
                                                    sout as a terminology for System.out.println();
Output obtained is : dob 10 name amit
Now change the object values d1.setHours(1); nameStr ="xyz";
Now output the values of the employee object
sout("dob "+ emp.getDob().getHours() + " name " +emp.getname());
Strange but output comes out to be "dob 1 name amit"
Note that in the above output the time for dob gets changed to 1. But we havent called the 
setter method for dob. This violates encapsulation. We obtained the above output because 
Date class is a mutable class,so both d1 and emp.Dob refers to the same memory location,
so change by any one gets reflected in the oher object. To avoid this always return a 
cloned object of the mutable classes. In the above case modify the getter method of 
dob as : 
public Date getDob() {
        return (Date)dob.clone();
    }

Input and Output


Output - System.out - This is an object not a class.
Input - System.in -See the example below
Scanner scan = new Scanner(System.in);
String str = scan.readLine();
Int a = scan.nextInt();
For password from the command prompt java6 introduces a Console class.
Console cons = System.console();
String username = cons.readLine("User name: ");
char[] passwd = cons.readPassword("Password: ");// password is returned as char array for security reasons

printf in java - Java 5 supports printf someehat similar to that of c. It is implemented to provide formated output.
eg double num = 1000.0/3.0;
System.out.printf("%8.2f",num); shows output as 333.33 (padded with 5 spaces from the left)

Blocks/Scope/Loops


Blocks are essential of any programming language. Java supports blocks.A block or compound statement is any number of simple Java statements that are surrounded
by a pair of braces. Blocks define the scope of your variables. Blocks can be nested inside another block.
public static void main(String[] args){
int a;
{
int k;
} //Scope of k limited till here only
}

Consider the case of shadowing a variable in inner block as in c/c++.
public static void main(String[] args){
int a;
{
int a;//Error as it is not allowed in java
}
}

Switch statement can use only int or enum type for cases. Nothing else is allowed.

Goto statement - In java goto is kept as a reserved keyword but java developers never implemented goto. The task of goto is accomplished by using "break label".
break label_name is used to break the control out of a block ,we cannot jump into another block.
label:
{
for(....)
{
while(...)
{
if(condition)
break label;
}
}
}

for each loop in java : syntax - for(datatype: array)
It is uesd to iterate the entire array. Read it as for each datatype in array
Eg int[] arr = new int[10];
for(int i = 0 ; i<>

Tuesday, January 18, 2011

Strings

Ok now lets talk about strings in java. Rather i should use Strings. Strings are itself not provided as a primitive data type by java like int. It is implemented with the help of String class in java.
eg String str="amit";
Most c users consider char str[] ="amit" as the implementation of the above declaration. But it is not true. The declaration resembles char *str="amit". The diffrence between the two is that the former is mutable (can change individual character values eg str[2]='a' ) but the latter is immutable.
Strings in java lie in between the implementation of primitive types and objects. Consider the following declaration :
String str="amit";
String str = new String("amit");
The former declaration uses the concept of primitive data types ie it data is not kept in user/program heap. All the variables declared in this style with the same value share the same memory space. Consider the following c illustration  :
char *temp ="str";
char *b = temp;
Both point to same memory location. Similarly String a="emp" and String b="emp" both share memory and point to the same location in java.( Try using if(a==b) though strictly not recommended. Since both point to same memory the output is true).
The latter places the string in the program heap so there is no concept of sharing.(Try comparing two strings with same value using == operator, the output comes out to be false.So use String.equals function for string comparison)
In java only + operator is overloaded for concatenation of two strings.

String class being immutable leads to slower string operations. For this StringBuffer( multiple thread) and StringBuilder ( single thread) class are provided.
They are mutable classes and does not overload the "+" operator as in String class.
PS: USe strings when data need not be modified frequently else use stringbuffer or StringBuilder.
For more details visist the following link : http://www3.ntu.edu.sg/home/ehchua/programming/java/J3d_String.html

Monday, January 17, 2011

First Program

Ok now its time to write the fisrt program in the language. I will be using plain text editor (notepad in windows) to write my very first program.

public Class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World");
}
}
We all know that the output of the program is Hello World. But have you ever tried to play with this basic program. Consider some of the few cases:
1.Make class HelloWorld as private/ protected and compile the program. Error occurs as "modifier private/protected" not allowed here".
2. Try removing public (default access specifier) and run the program. It turned out to be a surprise for me program compiled and ran successfully.
3. Try changing access type of main method to private/protected/default. Error message "Main method not public".
4. Change return type of main to int. Now here comes a surprise. The following method is compatible with java 1.3 and earlier versions. From version 1.4 onwards it gives error "java.lang.NoSuchMethodError".

Thats all for my first post.Do write reviews/comments. Further discussion will be highly appreciated.

PS: It is assumed in this blog that you are already aware of fundamentals of java.