Monday, 25 June 2012

JAVA -abstract class and interface

Both Abstract class and interfaces are both like frameworks or outer skeleton .

They are to be implemented in child class which extends the parent class .

1) Interface is solely a skeleton .
Abstract class is not solely a skeleton , it also has implementations within it .

2) As interface is solely a skeleton , all methods inside a interface are abstract methods and variables are final and static .So , the implementing child class should implement all the methods inside the interface .
But when creating interface , we need not put the keyword abstract in front of all methods inside an interface as the definition of interface means it .
Abstract class can have within it, variables that are non static , methods that are not abstract  . So , the child class that implements the abstract class should implement all the abstract methods (if any ) . And leave the non abstract methods untouched .Needs to explicitly say which methods are abstract using keyword "abstract".
Neither abstract class nor interface can be instantiated . It can be only be implemented .
So if we don't implement all methods of interface and all abstract methods of an abstract class , then it means the child class that implements these child classes will also be considered as interfaces or abstract classes ,as they contain abstract methods which was inherited   (not implemented) and so the child classes cannot be instantiated , as abstract class and interface cannot be instantiated .

This brings in the idea that abstract classes and interfaces can be extended by other interface or class . A class that extends an interface must me either another interface or abstract class . So here all the methods of the interface need not be implemented in abstract class that extends it.

3) As the interface is solely abstract or skeleton , it is implemented by using keyword "implements" and not by using keyword "extends". As abstract may have implementations within it . It is implemented using keyword "extends "
In fact a interface can extend another interface using keyword "extends"


4) a child class can extend many interfaces at the same time , by separating interface names with "," .
a child class can extend only one abstract class .

JAVA -methods and keyword "this" and "super"


Methods :

 Wikipedia says "Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property that at runtime, they have access to data stored in an instance of the class (or class instance or class object or object) they are associated with and are thereby able to control the state of the instance."  
So one thing is clear , during compilation the variables get set and  during run time the methods act on the variables of these instances . (Not sure)

Similar to variables we have 2 types
1) instance methods
2) class methods

Definitions are same as we saw in variables section .

Lets concentrate on which can access which ?

http://docs.oracle.com says

  • Instance methods can access instance variables and instance methods directly.
  • Instance methods can access class variables and class methods directly.
  • Class methods can access class variables and class methods directly.
  • Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
Lets not mug this up . Lets go by logic .

Instance methods are Object specific . so it can access that which are specific to instances(i.e., instance variables and methods ) and also those class methods and class variables which are common to all objects (as it knows which class's instance it is)
Class methods in not instance specific , it is common to all objects(or instances) , so it has no knowledge about the instance , as it is not instance specific . As it is totally unaware of the instances , it cannot access , instance variables and instance methods (which are instance specific) . Whereas it can access class methods and class variables .

So the keyword "this" is meaningless when used inside class methods .

Other classification : 
wikipedia gave three methods 

Abstract methods

An abstract method is one with only a signature and no implementation body. It is often used to specify that a subclass must provide an implementation of the method. Abstract methods are used to specify interfaces in some computer languages.[3]

[edit]Example

The following java code shows an abstract class that need to be extended:
abstract class Main{
 
        abstract int rectangle(int h,int w); //abstract method signature
}
The following subclass extends the main class:
public class Main2 extends Main{
 
        @Override
        int rectangle(int h,int w)
        {
                return h*w;
        }
 
}

Overloaded methods

http://java67.blogspot.in/2012/08/what-is-method-overriding-in-java-example-tutorial.html 
Overloaded methods are those with the same name but different formal parameters or return value type, if the language supports overloading on return type.[4] For example in the following C++, class geometry have two method named "area". But there parameter list is different which distinguish the methods. Many other languages provide this feature.
#include<iostream>
using namespace std;
class geometry
{
        public:
        static double area(double h,double w)
        {
                return h*w;
        }
        static double area(double r)
        {
                return r*r*3.14;
        }
 
};
int main()
{
        double rectangle_area=geometry().area(3,4);
        double circle_area=geometry().area(5);
        cout<<rectangle_area<<endl;
        cout<<circle_area<<endl;
        return 0;
}

[edit]Overridden methods

Overridden methods are those that are redefined in a subclass and hide methods of a superclass. It often creates confusion with overloaded methods. The main difference is overridden method is situated in a different class derived from a super class, while in case of overloaded method both methods can be in the same class. [5] Look at following example in java:
public class class1
{
        int f(int x)
        {
                return x+3;
        }
}
 
public class class2 extends class1
{
        @Override
        int f(int x) //overriding
        {
                return x*x;
        }
        int f(int x,int y) //overloading
        {
                return x*y;
        }
}

The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed.[2] Some languages allow a programmer to prevent a method from being overridden.

THIS :

For explanation on "this" refer the link below 

Inaddition read this 

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
    private int x, y;
    private int width, height;
        
    public Rectangle() {
        this(0, 0, 0, 0);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor.

Also refer 
Using "this" to return the instance that is using the class 


SUPER :

1) Used to call methods in superclass without the object name so no instantiation is needed to call super class's method .You may ask me question why we need this , when we can call using the object name.. Answer is this :this gives facility to access methods of super class from being inside child class .


public class Superclass {

    public void printMethod() {
        System.out.println("Printed in Superclass.");
    }
}

public class Subclass extends Superclass {

    // overrides printMethod in Superclass
    public void printMethod() {
        super.printMethod(); // calls the parent classes method printMethod
        System.out.println("Printed in Subclass");
    }
    public static void main(String[] args) {
        Subclass s = new Subclass();
        s.printMethod();    //calls the child classes method printMethod 
    }
}

2) Used to invoke superclass's constructor . .You may ask me that we already have this my using "this".
Ya , this calls constructor from inside the class whose constructor is called and not from outside the class .


The following example illustrates how to use the super keyword to invoke a superclass's constructor. Recall from the Bicycle example thatMountainBike is a subclass of Bicycle. Here is the MountainBike (subclass) constructor that calls the superclass constructor and then adds initialization code of its own:
public MountainBike(int startHeight, 
                    int startCadence,
                    int startSpeed,
                    int startGear) {
    super(startCadence, startSpeed, startGear);
    seatHeight = startHeight;
}   
Invocation of a superclass constructor must be the first line in the subclass constructor.
The syntax for calling a superclass constructor is
super();  
or:
super(parameter list);
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.




JAVA - Variable

Variables:

mostly 2 types
1) instance variable
2) class variable


Instance variable :

    Variables of each instance of a class varies . So same variable names of different instances(object) of same class , point to different memory location . So changing of its value by one object doesn't not get reflected in the variable of other object .

Class variables :

    Here  same variable names of different instances(object) of same class , point to same memory location . So a change made in the variable by one object , gets reflected in other objects variable , as these variables point to same memory location .

Next question that comes is how compiler differentiates between instance variables and class variables . Ya , we have to do that . We use the keyword "static" before variable name to denote it as class variables . Others are instance variables .



How to access these variables ?

Instance variable can be accessed by using the objectname(or so called instancename).instancevariable ;
Classvariable can be accessed by using the classname.classvariable ;


Application of the concept "static" to create constants :



The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).

 
  

Tuesday, 29 May 2012

Iterators


1)   for x in [1,4,5,10]:
...
print x


2) prices = { 'GOOG' : 490.10,
...
'AAPL' : 145.23,
...
'YHOO' : 21.71 }
...
>>> for key in prices:
...
print key


3) s = "Yow!"
>>> for c in s:
...
print c


In all the above for iteration , what is happening ?



items = [1, 4, 5]
>>> it = iter(items)
>>> it.next()
1
>>> it.next()
4
>>> it.next()
5
>>> it.next()
 
this is the underlying steps which are happening .

what does iter(items) do ..... it just returns iterator object ,,, which has inbuilt methods like next , stopiteration , etc ... after printing once , if the list is not empty , next () is exectued , so this process goes on and on , till list is empty , when the stopiteration is executed . 








Thursday, 24 May 2012

Python Utilities : 

We can do a number of things that we do in bash in unix , even in python interpreter .
one thing we have to do in 

import os 

now to see what are all the operations we can do  

EX_CANTCREAT
EX_CONFIG
EX_DATAERR
EX_IOERR
EX_NOHOST
EX_NOINPUT
EX_NOPERM
EX_NOUSER
EX_OK
EX_OSERR
EX_OSFILE
EX_PROTOCOL
EX_SOFTWARE
EX_TEMPFAIL
EX_UNAVAILABLE
EX_USAGE
F_OK
NGROUPS_MAX
O_APPEND
O_ASYNC
O_CREAT
O_DIRECT
O_DIRECTORY
O_DSYNC
O_EXCL
O_LARGEFILE
O_NDELAY
O_NOATIME
O_NOCTTY
O_NOFOLLOW
O_NONBLOCK
O_RDONLY
O_RDWR
O_RSYNC
O_SYNC
O_TRUNC
O_WRONLY
P_NOWAIT
P_NOWAITO
P_WAIT
R_OK
SEEK_CUR
SEEK_END
SEEK_SET
ST_APPEND
ST_MANDLOCK
ST_NOATIME
ST_NODEV
ST_NODIRATIME
ST_NOEXEC
ST_NOSUID
ST_RDONLY
ST_RELATIME
ST_SYNCHRONOUS
ST_WRITE
TMP_MAX
UserDict
WCONTINUED
WCOREDUMP
WEXITSTATUS
WIFCONTINUED
WIFEXITED
WIFSIGNALED
WIFSTOPPED
WNOHANG
WSTOPSIG
WTERMSIG
WUNTRACED
W_OK
X_OK
_Environ
__all__
__builtins__
__doc__
__file__
__name__
__package__
_copy_reg
_execvpe
_exists
_exit
_get_exports_list
_make_stat_result
_make_statvfs_result
_pickle_stat_result
_pickle_statvfs_result
_spawnvef
abort
access
altsep
chdir
chmod
chown
chroot
close
closerange
confstr
confstr_names
ctermid
curdir
defpath
devnull
dup
dup2
environ
errno
error
execl
execle
execlp
execlpe
execv
execve
execvp
execvpe
extsep
fchdir
fchmod
fchown
fdatasync
fdopen
fork
forkpty
fpathconf
fstat
fstatvfs
fsync
ftruncate
getcwd
getcwdu
getegid
getenv
geteuid
getgid
getgroups
getloadavg
getlogin
getpgid
getpgrp
getpid
getppid
getresgid
getresuid
getsid
getuid
initgroups
isatty
kill
killpg
lchown
linesep
link
listdir
lseek
lstat
major
makedev
makedirs
minor
mkdir
mkfifo
mknod
name
nice
open
openpty
pardir
path
pathconf
pathconf_names
pathsep
pipe
popen
popen2
popen3
popen4
putenv
read
readlink
remove
removedirs
rename
renames
rmdir
sep
setegid
seteuid
setgid
setgroups
setpgid
setpgrp
setregid
setresgid
setresuid
setreuid
setsid
setuid
spawnl
spawnle
spawnlp
spawnlpe
spawnv
spawnve
spawnvp
spawnvpe
stat
stat_float_times
stat_result
statvfs
statvfs_result
strerror
symlink
sys
sysconf
sysconf_names
system
tcgetpgrp
tcsetpgrp
tempnam
times
tmpfile
tmpnam
ttyname
umask
uname
unlink
unsetenv
urandom
utime
wait
wait3
wait4
waitpid
walk
write

Now we shall see some examples 

to list contents of dirctory 

os.listdir(directoryname)
list filenames in the directory 

os.path.exists( ) 
to see is the path exists

to do file copy 

import shutil
shutil.copy(source,dest) 

both strings source and dest denote filenames with path 

we cannot do it for copying entire folder content , this can be done by iterating over files inside the folder
Ok these are ways to simulate shell commands in python

Is there a way to run shell commands directly in python and show output 

Ya

import commands 
cmd = "ls -l ."
(status,output) = commands.getstatusoutput(cmd)
print output

this executes ls -l command on directory .  gives the output as a tuple having 2 things ., status (something like exit code, if 0 it means the command executed without error , if command execution had error it exits by sending 1 or even some other error code like 512 ) and the output of the command 


Interesting feature in python :

List comprehension 

if we have a list a = [1, 2 ,3,4]
then you want to get a new list which has the squares of these numbers ..
what we normally do is iterate through the list then get elements and then put it into the new list 

python has a easy way of doing this

b = [num*num      for num in a]

to put additional qualities like removing elements < 2 

b=[num*num     for num in a     if num>2]

Wednesday, 23 May 2012

Python

Dictionary in python :


Dictionary is basically key value binding .
As String is enclosed within " "
As List is enclosed within    [  ]
As tuple is enclosed within  (  )

Here dictionary ,it is enclosed within  {  }

In String , list tuple , also we have this same idea ,,, but there key is always an integer ... so we call it index

So  Stringname or listname or tuplename [1] means , item at index 1

Dictionary gives scope for having having even non integer keys

To declare a Dictionary :   d = { }

>>d['a'] = 'alpha'
>>d['o']='omega'
>>d['g']='gamma'

this is the way to assign value in a dictionary .

Now,  to retrieve a value in String or list or tuple , what will u do ,?  name[index]

similarly here  >>d['a']  displays   'alpha'

The advantage of having key and corresponding value storage is that , it is fast at retrieval using key ,,
this is the advantage of hashtable

But don't know why it is faster in this way .........
 
If you give d['x'] , it flings an error , as the key x is not there in dictionary d .

So , what can be the way to bypass , this even if the key is not there , but still , not flag an error ,,
this can be used in future to check if a key exists in a dictionary ..

Ya, we have a 2 solutions

1) d.get['x]  returns value null if key x is not found and returns the actual corresponding value if the key exists

>>d.get['a']  returns  'alpha'
2) As , we do in lists is ,a =[1,2,3]
to find if 2 is a value inside it ,, we say  2 in a   , returns true if 2 value is there  (note that here we r searching by value , so this time is longer )
Here also same thing

'a' in d  returns true if key 'a' exists , false if it doesn't exist

To see the list of keys at once in a dictionary 

d.keys()

To see the list of values at once in a dictionary

d.values()

To get values ,,, just loop over

for k in d.keys() :
    print d[k]

to have it ordered

for k in sorted(d.keys()):
   print d[k]


To see list of key value pair .

d.items() ...............returns

[('a','alpha') , ('o','omega'),('g','gamma')]

looping over  ? ya , easy
for tuple in d.items() :
    print tuple


File operation in Python : 

f = open(filename , 'r')

the second argument indicates , whether we r opening file for reading or 'w' denotes 'writing .. similary we have 'rU'

f is here the file handler ,,,  by this line we just open the file and give it to f  ,, from f we can read it
now we can iterate each line ,,as soon as it sees a new line in f  ( which is a reflection of file filename which is open ), it stops ,reading ,
like this we iterate over every line

for line in f:
    print line

prints each line but with double line space between

this is because print itself has a new line and the new line in file adds to it ,,
so to eliminate it replace print statement by
print line,

the trailing comma removes this problem as it removes the new line in the print

finally , we have to close the open file ,,as a open file unnecessarily draws memory

f.close()

if u omit this line , when the process ends the file is closed automatical
but in case of softwares which r continuously running , the process also runs , so here if we don't close, it remains open the whole period of time , when software runs ,and that too unnecessarily
what is the advantage of having this concept of reading line by line ? why not read at once

when we read , big files say 90 Gb ,,  reading at once gives problem of locking heavy memory

when we read line by line only a small part of memory is locked for its work ,

f.readlines()

gives o/p as a list of lines

['line1' ,'line2','line3'...]

it even prints it in the same way as shown above

f.read()

reads entire file into a single string

so has same view as we open a file in editor in gui

Thursday, 26 January 2012

POP



POP , otherwise known as Post office protocol , is a protocol used by the email-clients to retrieve emails from a remote server over a TCP/IP connection.

let us try retrieving mail from my gmail account without using any client ,starting from scratch.

gmail uses POP and IMAP , Let us for the time being concentrate on POP.

wikipedia page on POP gives information which reads

"A POP3 server listens on port 110. Encrypted communication for POP3 is either requested after protocol initiation, using the STLS command, if supported, or by POP3S, which connects to the server using secure sockets layer (SSL) on well-known TCP port 995 (e.g. google Gmail)."

so I need to connect using SSL protocol( this is needed because gmail has SSL security layer protection)

The openssl command does this job . By the way i, need to create a client where i can view the mails . This is also done by passing s_client as argument for this openssl command

$openssl s_client

wait ,dont execute this command in command line, the command is not yet over,
we need to connect it to the gmail POP server ( gmail server that uses POP protocol) , so

$openssl s_client -connect pop.gmail.com:995

we can get the port number detail from wikipedia information i quoted above.

so now ,the task that we have completed so far are

1) client has been created

2) client communictaes using SSL ( this is needed because gmail has SSL security layer protection)

3) We have established connection between the client the POP gmail server

thats all, the rest is what we do in the GUI ....

Just give username , password and then read the mail
So the next thing that we need to type is shown in color

user <type your user name here>

And Another Kind Request :
Chase those fellows standing near by , because the password is exposed as you type.

pass <type your user password here>
STAT
LIST
retr <type the mail number of the mail you wanted to read by seeing the list dispalyed>


after reading the mail ,you can quit and signout using command

quit

Thats all I know about POP .

Bye ,

Harish Kayarohanam