Monday, December 6, 2010

instance of in JAVA

Sometimes, knowing the type of an object during run time is useful. For example, you might have one thread of execution that generates various types of objects, and another thread that processes these objects. In this situation, it might be useful for the processing thread to know the type of each object when it receives it. Another situation in which knowledge of an object's type at run time is important involves casting. In Java, an invalid cast causes a run-time error. Many invalid casts can be caught at compile time. However, casts involving class hierarchies can produce invalid casts that can be detected only at run time. For example, a superclass called A can produce two subclasses, called B and C. Thus, casting a B object into type A or casting a C object into type A is legal, but casting a B object into type C (or vice versa) isn't legal. Because an object of type A can refer to objects of either B or C, how can you know, at run time, what type of object is actually being referred to before attempting the cast to type C? It could be an object of type A, B, or C. If it is an object of type B, a run-time exception will be thrown. Java provides the run-time operator instanceof to answer this question.
The instanceof operator has this general form:

object instanceof type

Here, object is an instance of a class, and type is a class type. If object is of the specified type or can be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus, instanceof is the means by which your program can obtain run-time type information about an object.

The following program demonstrates instanceof:

// Demonstrate instanceof operator.
class A {
int i, j;
}
class B {
int i, j;
}
class C extends A {
int k;
}
class D extends A {
int k;
}
class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if(a instanceof A)
System.out.println("a is instance of A");
if(b instanceof B)
System.out.println("b is instance of B");
if(c instanceof C)
System.out.println("c is instance of C");
if(c instanceof A)
System.out.println("c can be cast to A");
if(a instanceof C)
System.out.println("a can be cast to C");
System.out.println();
// compare types of derived types
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if(ob instanceof D)
System.out.println("ob is instance of D");
System.out.println();
ob = c; // A reference to c
System.out.println("ob now refers to c");
if(ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if(ob instanceof A)
System.out.println("ob can be cast to A");
- 230 -
System.out.println();
// all objects can be cast to Object
if(a instanceof Object)
System.out.println("a may be cast to Object");
if(b instanceof Object)
System.out.println("b may be cast to Object");
if(c instanceof Object)
System.out.println("c may be cast to Object");
if(d instanceof Object)
System.out.println("d may be cast to Object");
}
}

The output from this program is shown here:

a is instance of A
b is instance of B
c is instance of C
c can be cast to A
ob now refers to d
ob is instance of D
ob now refers to c
ob cannot be cast to D
ob can be cast to A
a may be cast to Object
b may be cast to Object
c may be cast to Object
d may be cast to Object

The instanceof operator isn't needed by most programs, because, generally, you know the type of object with which you are working. However, it can be very useful when you're writing generalized routines that operate on objects of a complex class hierarchy

Private final methods

If one class have one private final method so what happen if another class is try to overridden the same method in another class:
for reference check the below example

class Raptor{
private final void test(){
System.out.println("i am final of Raptor");
}
}

class Hawk extends Raptor {
public final void test(){
System.out.println("i am the final of Hawk");
}

public static void main(String[] args) {
Hawk hawk_obj = new Hawk();
hawk_obj.test();
}
}

Result:
compile and program may run the output is "i am the final of Hawk", because the test function is private and it'll never available in another class so the final method never be override in another class rule is not applicable.

Java Constructor don't have return type:

Constructor never return in Java and if you see the constructor have return type, so it's not a constructor it's a method with the same name of class...
class Bird {
public String Bird() {
return ("I am bird");
}
public static void main (String args[]){
Bird b - new Bird(); // object creation and assign the Reference to variable
b.Bird(); // now the function call
}

Good use of static, constructor and init blocks

class Bird {
{
System.out.print("b1 ");
}

public Bird() {
System.out.print("b2 ");
}
}

class Raptor extends Bird {
static {
System.out.print("r1 ");
}

public Raptor() {
System.out.print("r2 ");
}

{
System.out.print("r3 ");
}
static {
System.out.print("r4 ");
}
}

class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();

System.out.println("hawk ");
/*Raptor rap = new Raptor();
if (rap instanceof Raptor){
System.out.println("i m working");
}*/
}
}


Guess what is the answer: r1 r4 pre b1 b2 r3 r2 hawk
static always related with class not with instance so they run when the class initialized, next turn for constructor but here we have init blocks so first the init blocks have run then the constructor come in picture from top to bottom, super class init => constructor => child class init => constructor...

Friday, August 13, 2010

Serialization (Store the Objects) and Deserialization (Restore the objects) in Java

Serialization:
Objects have a state and behavior.
Behavior (methods) lives Class (in memory term Stack), state (instance variable) lives with in each objects (Heap), serialization is the way to save the state of object.
If you are writing a game, you're gonna need a Save/Restore Game Feature.

Deserialization: the whole point of serializing an object is so that you can restore it back to the original state at some later date, in a different run of JVM (which might not even be the same JVM that was running at the time the object was serialized).
Deserialization is lot like serialization in reverse.


import java.io.*;
import java.lang.*;

class Model implements Serializable {//mandatory to implement serializable interface(contains not any method).
int id;

String name;

public Integer getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

}
}

public class SampleProgram {

public static void main(String args[]) {
Model model = new Model();
model.setId(10);
model.setName("aayush");

System.out.println("the out put before serialize " + model.getId()
+ " " + model.getName() + " i am going to finish");
try {

System.out.println("Serialize start");
//create a file or use a existing file.
FileOutputStream file = new FileOutputStream("inpu.ser");
//connect the file like from source to destination
ObjectOutputStream obj = new ObjectOutputStream(file);
//writing object
obj.writeObject(model);
//closing
obj.close();

}
catch (Exception ex) {

ex.printStackTrace();

}
//declare reference value null
model = null;

try {
System.out.println("i am going to restore");
//restoring start
ObjectInputStream restore = new ObjectInputStream(
new FileInputStream("inpu.ser"));
//reading object with type cast
Model model_restore = (Model) restore.readObject();
//closing
restore.close();
//output
System.out.println(model_restore.getName());

}
catch (Exception exe) {
exe.printStackTrace();
}

}
}

Friday, August 6, 2010

Is OuterClass able to access the InnerClass Methods and Variables (Vice-Versa)?

In Main method both classes are unable to access the variables and methods but outside the Main method InnerClass has a right to access the OuterClass variables and Methods (even private also), but what about the OuterClass?
OuterClass has also right to access the InnerClass Variables and Methods...

How : innerclass_object and outerclass_obect
These two objects on the heap have a special bond, The inner can use the outer's variable (and vice-versa).

See the example:


public class OuterClass {
private String str;

// create the instance of innerclass...
InnerClass obj = new InnerClass();

private class InnerClass {
int i;

public int getI() {

// intialize the outerclass private variable
str = "aayushjain";
System.out.println(str);
return i;
}

public void setI(int i) {
this.i = i;

}

}

public void trial() {
System.out.println("hello i from outerclass");

// call the Inner Class methods
obj.setI(100);
System.out.println(obj.getI());
}

public static void main(String args[]) {
OuterClass obj_out = new OuterClass();

// unbale to access the innerclass methods.....
/* obj_out.getI(); */

OuterClass.InnerClass obj_inner = obj_out.new InnerClass();

obj_inner.setI(10);
System.out.println(obj_inner.getI());

// unable to access the outerclass methods..
/* obj_inner.trial(); */
obj_out.trial();

}
}

Thursday, August 5, 2010

How to Bulk file Rename in Linux

How to Bulk Rename Files in Linux (Terminal or GUI)

If you have a directory of files that you would like to bulk rename, you can use the rename command from the terminal.

The syntax for the rename command is:

rename [ -v ] [ -n ] [ -f ] perlexpr [ files ]

-v means "verbose" and it will output the names of the files when it renames them. It is a good idea to use this feature so you can keep track of what is being renamed. It is also a good idea to do a test run with -n which will do a test run where it won't rename any files, but will show you a list of files that would be renamed.

Here is an example of the rename command:

rename -n ’s/\.htm$/\.html/’ *.htm

The -n means that it's a test run and will not actually change any files. It will show you a list of files that would be renamed if you removed the -n. In the case above, it will convert all files in the current directory from a file extension of .htm to .html.

If the output of the above test run looked ok then you could run the final version:

rename -v ’s/\.htm$/\.html/’ *.htm

The -v is optional, but it's a good idea to include it because it is the only record you will have of changes that were made by the rename command as shown in the sample output below:

$ rename -v 's/\.htm$/\.html/' *.htm
3.htm renamed as 3.html
4.htm renamed as 4.html
5.htm renamed as 5.html

The tricky part in the middle is a Perl substitution with regular expressions, highlighted below:

rename -v ’s/\.htm$/\.html/’ *.htm

Tip: There is an intro to Perl regular expression here

Basically the "s" means substitute. The syntax is s/old/new/ — substitute the old with the new.

A . (period) has a special meaning in a regular expression — it means "match any character". We don't want to match any character in the example above. It should match only a period. The backslash is a way to "escape" the regular expression meaning of "any character" and just read it as a normal period.

The $ means the end of the string. \.htm$ means that it will match .htm but not .html.

It's fairly basic — substitute .htm with .html:

's/\.htm$/\.html/'

The last part of the command, highlighted below, means to apply the rename command to every file that ends with .htm (the * is a wildcard).

rename -v ’s/\.htm$/\.html/’ *.htm

Other Example
Maybe you have a digital camera that takes photos with filenames something like 00001234.JPG, 00001235.JPG, 00001236.JPG. You could make the .JPG extension lowercase with the following command executed from the same directory as the images:

rename -v 's/\.JPG$/\.jpg/' *.JPG

Here is the output of the above command:

$ rename -v 's/\.JPG$/\.jpg/' *.JPG
00001111.JPG renamed as 00001111.jpg
00001112.JPG renamed as 00001112.jpg
00001113.JPG renamed as 00001113.jpg

That is simple enough, as it is similar to the .html example earlier. You could also bulk rename them with something descriptive at the beginning like this:

Tip: Before trying more complicated renaming like in the example below, do a test run with the -n option as described at the beginning of this tutorial.

rename -v 's/(\d{8})\.JPG$/BeachPics_$1\.jpg/' *.JPG

or you can combine the two commands like below example

find -name '*.JPG' | rename -v 's/(\d{8})\.JPG$/BeachPics_$1\.jpg/' *.JPG

Friday, July 30, 2010

Java Static Function

Q. Can we override the Static function in Java ?
A. Yes we can override the Static function in Java see the sample recipe

class Sample implements Over {

public static int simple(int a, int b) {
int c = a + b;
return c;
}
}
class Overloading extends Sample {

public static int simple(int a, int b) {
int c = a * b;
return c;

}
public static void main(String[] args) {
        Sample sam = new Sample(22, 90);
        Overloading obj = new Overloading();
          obj.simple(10,20); // here the sub class function call
         sam..simple(10,20); // here the super class function call
}
}


Saturday, February 6, 2010

Type Hint in PHP

Type Hint in PHP.
Day by day PHP introduces new strong OOPS concepts earlier i used the Type Hinting (earlier it's available in Hot cup of Java) in type hint we restrict the input type parameter like this:

class DAO{function add(Model $model){}}
here we restrict the input parameter is object type & also object of Model class.
but yet it's have some limitation, available for object and array not for integer, float etc

Sunday, January 24, 2010

PHP Unit Test Case

How to Install PHPUnit Test ?
1. First Create the environment variable of pear:
check where u install the php /usr/local/php/bin/
2. open the file : /etc/environment
3. add the path in PATH
4. logout (otherwise environment not reflect)
5. sudo /usr/local/php/bin/pear channel-discover pear.phpunit.de
6. if after the above command he is asking for upgrade the pear:
7. use this command : sudo usr/local/php/bin/pear upgrade PEAR
8. sudo usr/local/php/bin/pear install phpunit/PHPUnit

now start programming.