Thursday, September 26, 2013

Java: Anonymous Inner class




Anonymous Inner class

 

Note :Used in conjunction with Abstract Class or Interfaces

Example :

public class Test1 {

    public static void main(String[] args) {

        x obj=new x(){
                void disp() {System.out.println("Hi");}
                };
        obj.disp();
    }

}


abstract class x{   
    abstract void disp();
}

 

 Output: Hi

 


Use it as a shortcut for attaching an event listener:

Example:

button.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e)

    {

        // do something.

    }

});


  • Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener --
  •  I can just instantiate an anonymous inner class without actually making a separate class.
  • I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.



Java : Abstract Class VS Interfaces


Abstract Class VS Interfaces

 

 


Abstract Class VS Interfaces
Inheritance :

class animal{
void eat(){System.out.print("animal eat");}
}

class dog extends animal {
}

class Test {
public static void main(String[] args){
dog d=new dog();
d.eat(); // instance dog can inherit animal property
}
}


Abstract Class :

abstract class animal{
void eat(){System.out.print("animal eat");}
abstract void noise(); // No definition
}

//dog class can inherit all properties except method declared as abstract
//Abstract method needs to be defined explicitly in the subclass ie., dog

class dog extends animal {
void noise(){System.out.print("bark");}
}

class Test {
public static void main(String[] args){
dog d=new dog();
d.eat();
d.noise();
}
}

Ref : http://www.javacoffeebreak.com/faq/faq0084.html
To summarise:
1.Use abstract classes- can inherit all methods except ones declared as abstract.Abstract method should be declared explicitly in the calling method Ex :all animals eat,sleep but make different sound(sound can be made abstract which is explicitly defined in subclass)

2.Use interfaces - here all methods are abstract by default and everything has to be implemented (once implemented gives you a skeleton on things needs to be defined )
Interface:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.


/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}


/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){System.out.println("Mammal eats"); }

public void travel(){ System.out.println("Mammal travels");}

public int noOfLegs(){return 0; }

public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}



4) NOTE:
Using an abstract class, you can have functions, that dont need to get implemented by the classes inheriting the abstract class. (http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
Using an interface, every subclass has to define every method, provided by this interface. (http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
Use an abstract class when you want to make one or more methods not abstract.
If you want to keep all abstract, use an interface.
5) Links
http://www.javatpoint.com/abstract-class-in-java
http://www.programmerinterview.com/index.php/java-questions/interface-vs-abstract-class/

--------------------------------------------------
Uses of Interface
One reason I use interfaces is because it increases the flexibility of the code. Let's say we got a method that takes an object of class type Account as parameter, such as:

public void DoSomething(Account account) {
// Do awesome stuff here.
}

The problem with this, is that I have to send only Account object as a parameter.
Take this below example, which instead uses an account of type= Interface as parameter.

public void DoSomething(IAccount account) {
// Do awesome stuff here.
}

This solution is not fixed towards an implementation, which means that I can pass it a SavingsAccount or a JointAccount or CurrentAccount (both who has implemented the IAccount interface ie., ) and get different behavior for each implemented account.

------------------------------------------------------------------------------------------

Uses of Interface

One of the many uses I have read is where its difficult without multiple-inheritance-using-interfaces in Java :

class Animal
{
void walk() { }
....
.... //other methods and finally
void chew() { } //concentrate on this
}
Now, Imagine a case where:

class Reptile extends Animal
{
//reptile specific code here
} //not a problem here
but,

class Bird extends Animal
{
...... //other Bird specific code
} //now Birds cannot chew but Bird classes can also call chew() method which is unwanted

Better design would be:

class Animal
{
void walk() { }
....
.... //other methods
}

Animal does not have the chew() method and instead is put in an interface as :

interface Chewable {
void chew();
}

and have Reptile class implement this and not Birds (since Birds cannot chew) :

class Reptile extends Animal implements Chewable { }

and in case of Birds simply:

class Bird extends Animal { }
-------------------------------------------------------
Rules for using Abstract ,Interface ,extending a class

Java interface is like a 100% pure abstract class.You MUST implement all abstract methods
Concrete class
-normal class - when your new class doesn’t pass the IS-A test for any other type.

When To extend a class ?
-when u need to add new behaviors and Passes IS-A.

How to implement Has -A functionality in an object ?
-Instance Variable or class variable
When To Use an abstract class -
A template for a group of subclasses and you have at least some implementation code that all subclasses could use.
when you want to guarantee that nobody can make objects of that type.
Abstract class uses methods as well as abstract methods

Use an interface -

when 100% abstract and static methods is allowed
when you want to define a role that other classes can play

--------------------------------------------------------
interface tree{
production();
}

class mango implements tree{
production(){}
}

class grape implements tree{
production(){}
}

psvm[]{
tree t=new mango();
tree t=new grape();
}

now user can create a new tree type like strawberry , orange etc., which has implement tree and use --
tree t=new orange();

ref:
http://catchbug.blogspot.in/2015/06/jave-excellent-interface-example.html





Tuesday, September 17, 2013

misc : What is RWD


RWD

What is Responsive Web Design?

 

 A responsive website changes its appearance and layout based on the size of the screen the website is displayed on.






 

 Responsive sites can be designed to make the text on the page larger and easier to read on smaller screens. They can also be configured to make the buttons on the phone's screen easier to press.


Misc : What is BootStrap

Boot Strap

" it's a simple file that starts a large process."

 

"Rather than the user downloading the entire app, including features he does not need, and re-downloading and manually updating it whenever there is an update, the user only downloads and starts a small "bootstrap" executable, which in turn downloads and installs those parts of the application that the user needs. Additionally, the bootstrap component is able to look for updates and install them each time it is started."

 


"...is a technique by which a simple computer program activates a more complicated system of programs."

 

"A different use of the term bootstrapping is to use a compiler to compile itself, by first writing a small part of a compiler of a new programming language in an existing language to compile more programs of the new compiler written in the new language." 

 

What is Twitter Boot-strap ?

http://wearepropeople.com/blog/twitter-bootstrap-the-ultimate-resources-roundup

http://www.w3resource.com/twitter-bootstrap/tutorial.php

 

Friday, September 13, 2013

Selenium : BreakPoints

BreakPoints 

BreakPoint :

  1. In the Eclipse Editor , Double click on the margin right next to the code where you want the code to break.
  2. You will see a circle.

DeBug

  1.  Eclipse>Run > Debug

View contents of Variables (Watch)

  1. Select and Hightlight the variable you want to watch.
  2. Rt click>Watch


Selenium : How to Display Exception

How to Display Exception

 

Example Below : 

---------------------------------------------------------------------------------------------------------------

try {
    throw new RuntimeException("hu?");
} catch (Exception e) {
    System.out.println(e.getMessage()); 
}
 

---------------------------------------------------------------------------------------------------------------


QTP: QTP Addins

QTP: QTP Addins

I think this link is little or no help unless you have an account with Hp.

http://relevantcodes.com/qtp-11-0-patches/

Thursday, September 12, 2013

Selenium :Eclipse Workspace Color Setting

Eclipse Workspace Color Setting

WorkSpace Editor 
Eclipse > Window > Preferences > General > Editors > Text Editors.

Color Theme Change
Eclipse > Window > Preferences >  Java > Editor  > Syntax Coloring

Font Size and Style
Eclipse>Window>Preferences> Appearence>Colors and Fonts >Java>Java Editor Text> Edit

Detach Window
You can right-click on the title of any "View" and choose "Detach", this way you won't need two mail windows

Change match highlight:
General->Editors->Text Editors->Annotations->Occurences.

Personal Color Setting
General Schema:
  1. selection: Green
  2. background: Grey
Java Editor :
Eclipse > Window > Preferences >  Java > Editor  > Syntax Coloring 
  1. method :  Color-black, italic
  2. method declaration:  Color-black ,italic ,Underline
  3. classes:  Dark Black, Bold
  4. static method invocations :  Color-(6th col from left,3rd row from bottom),Strike-through
  5. static Fields :   Strike-through,italic,Color-(6th col from left,3rd row from bottom)
  6. Comments - Italic ,color ( last row 5th col) 
  7. Strings:bold(3rd col from left,3 rd row from last row
  8. fields : default color (6th col from left,3rd row from bottom)+ italic (fields are variables declared inside a class).
  9. Window >> Preferences� >> Java >> Editor. Select Highlight matching brackets (yellow)
  10. Font  : Consoles , Size=9 

Selenium : Eclipse Themes

Selenium : Themes


Check out this website for customizing Eclipse 


  1. Download any Theme of "epf" format.
  2.  Eclipse>File>Import>General>Preferences>next
  3.  Select the ".epf" File>Finish
Please check the below website as well :

Removing the Theme : 

  1. Goto : workspace\.metadata\.plugins\org.eclipse.core.runtime\.settings". 
  2. Delete all the contents
  3. Restart Eclipse 

 



Wednesday, September 11, 2013

Selenium : Fetch Data from Excel using Query (Better Version)

Fetch Data from Excel using Query  (Better Version)

Link to download JAR files for Apache POI : http://poi.apache.org/download.html#POI-3.9 and http://www.apache.org/dyn/closer.cgi/poi/release/bin/poi-bin-3.9-20121203.zip (might change according to the new update ).

Configuration :
http://catchbug.blogspot.in/2013/04/selenium-connect-to-excel-spreadsheet.html



public class Sample1
{
public static void main(String[] args)
{
Object oData=Excel.DB_Read("Datasheet", "Select Label,Xpath from [Sheet1$] where Module='Module 1'");
System.out.println(oData);
oData.toString();
}
}

class Excel{
public static Object DB_Read(String sWb,String sQuery)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:"+sWb);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sQuery);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount(); //Get Column Count

Object columnValue ="";// null;
while (rs.next())
{
for (int i = 1; i <= numberOfColumns; i++)
{
columnValue = columnValue+rs.getString(i);
if (i != numberOfColumns)
columnValue = columnValue+"|";
}
columnValue=columnValue+"\n";
}
st.close();
con.close();
return columnValue;
}
catch (Exception ex)
{
System.err.print("Exception: ");
System.err.println(ex.getMessage());
return null;
}
}
}

Selenium : Hash Code

Hash Code



A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable.

Imagine the following simple example:


On the table in front of you have 9 boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.


What you need is a way of instantly deciding which box you have put each object in. It works like an index; you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.


Now imagine that you don't want to bother with the index, you want to be able to find out immediately from the object which box it lives in.


In the example, let's use a really simple way of doing this - the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. What about the rhinoceros, though? It has 10 characters, so we'll change our algorithm a little and "wrap round" so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.
Sometimes a box will have more than one object in it, but if you are looking for a rocket, it's still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas , banjos and rhinoceroses.


That's a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java a hash code can be any integer, and each object type is responsible for generating its own. Lookup the "hashCode" method of Object.

Tuesday, September 10, 2013

Selenium : Creating Object Repository

Creating Object Repository



Since the "OR" File resides in the same package there is no need to import .


------------------------File Name : Sample1.java --------------------File1
public class Sample1
{
    public static void main(String[] args)   
    {       
        WebDriver oDriver=new FirefoxDriver();
        oDriver.get("https://www.google.co.in");
        WebElement oTitle=oDriver.findElement(By.xpath(OR.button));  // Directly using the static variable     }
}

===================================================================

------------------------File Name : OR .java--------------------File2
public class OR {

          public static final String button="//button[@id='gbqfba']";
       
}
===================================================================

Selenium : Final Keyword

Selenium : Final Keyword

Final is different than finally keyword which is used on Exception handling in Java. 

Final variable 
  1. It must be initialized at the time of declaration or inside constructor. 
  2. Once you make a initialized final you are not allowed to change it and compiler will raise compilation error if you try to re-initialized final variables in java. 
  3. Final variables are often declare with static keyword in java and treated as constant. 

Example :
public static final String sVar = "some_Data";
sVar = "HI"; //invalid compilation error
sVar = new String("new_data"); //invalid compilation error

  final method
  1. Final keyword in java can also be applied to methods.
  2.  You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. 
  3. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.
Example:
class Loan
 {
 public final String getName()
{
     return "personal loan";
 }
}
class PersonalLoan extends Loan
 {
    @Override
    public final String getName()
 {
        return "cheap personal loan"; //compilation error: overridden method is final
    }
}

  final Class in Java

  1.   Final class is complete in nature and can not be sub-classed or inherited. 
  2. Several classes in Java are final e.g. String, Integer and other wrapper classes. 
Example :
final class Loan
 {
}
class PersonalLoan extends Loan 
{  //compilation error: cannot inherit from final class
 
}

Benefits of final keyword in Java

1. Final keyword improves performance.
2. Final variables are safe to share in multi-threading environment without additional synchronization overhead.