object class methods in java

Upload: md-imam

Post on 03-Jun-2018

250 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Object Class Methods in Java

    1/35

    We are going to discus about Object Class Methods in Java. The java.lang.Object class is

    the root of the class hierarchy tree in JDE(java developent environent!. Every Java

    class e"tends the java.lang.Object class directly or indirectly. There are any ethods

    defined in java.lang.Object class these are as clone(!# e$uals(!# finali%e(!# notify(!#

    notify&ll(!# getClass(!# to'tring(!# ait(!# etc

    Class java.lang.Object

    java.lang.Object

    public class Object

    Class Objectis the root of the class hierarchy. Every class has Objectas a superclass. All

    objects, including arrays, implement the methods of this class.

    'ee &lso)

    Class

    Object()

    clone()

    Creates a new object of the same class as this object.

    e$uals(Object)

    Compares two Objects for euality.finali%e()

    Called by the garbage collector on an object when garbage collection determines thatthere are no more references to the object.

    getClass()

    !eturns the runtime class of an object.

    hashCode()

    !eturns a hash code value for the object.

    notify()"a#es up a single thread that is waiting on this object$s monitor.

    notify&ll()

    "a#es up all threads that are waiting on this object$s monitor.to'tring()

    !eturns a string representation of the object.

    ait()

    "aits to be notified by another thread of a change in this object.

    ait(long)

    "aits to be notified by another thread of a change in this object.

    ait(long, int)

    http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Class.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#Object()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#clone()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#equals(java.lang.Object)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#finalize()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#getClass()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#hashCode()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#toString()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait(long)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait(long,%20int)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#Object()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#clone()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#equals(java.lang.Object)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#finalize()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#getClass()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#hashCode()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#toString()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait(long)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait(long,%20int)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Class.html#_top_
  • 8/12/2019 Object Class Methods in Java

    2/35

    "aits to be notified by another thread of a change in this object.

    Objectpublic Object()

    getClasspublic final native ClassgetClass()

    !eturns the runtime class of an object.

    *eturns)

    the object of type Classthat represents the runtime class of the object.

    hashCodepublic native int hashCode()

    !eturns a hash code value for the object. %his method is supported for the benefit of

    hashtables such as those provided by java.util.Hashtable.

    %he general contract of hashCodeis&

    "henever it is invo#ed on the same object more than once during an e'ecution of

    a ava application, the hashCodemethod must consistently return the same

    integer. %his integer need not remain consistent from one e'ecution of an

    application to another e'ecution of the same application.

    f two objects are eual according to the equalsmethod, then calling the

    hashCodemethod on each of the two objects must produce the same integer

    result.

    *eturns)

    a hash code value for this object.

    'ee &lso)

    euals, *ashtable

    e$ualspublic boolean equals(Objectobj)

    Compares two Objects for euality.

    %he equalsmethod implements an euivalence relation&

    t is reflexive& for any reference value x, x.equals(x)should return true.

    t issymmetric& for any reference values xand y, x.equals(y)should return

    trueif and only if y.equals(x)returns true.

    t is transitive& for any reference values x, y, and z, if x.equals(y)returns true

    and y.equals(z)returns true, then x.equals(z)should return true.

    http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Class.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#equals(java.lang.Object)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.util.Hashtable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Class.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#equals(java.lang.Object)http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.util.Hashtable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#_top_
  • 8/12/2019 Object Class Methods in Java

    3/35

    t is consistent& for any reference values xand y, multiple invocations of

    x.equals(y)consistently return trueor consistently return false.

    +or any reference value x, x.equals(null)should return false.

    %he euals method for class Objectimplements the most discriminating possible

    euivalence relation on objects that is, for any reference values xand y, this method

    returns trueif and only if xand yrefer to the same object (x==yhas the value true).

    +araeters)

    obj - the reference object with which to compare.

    *eturns)

    trueif this object is the same as the obj argument falseotherwise.

    'ee &lso)

    hashCode,*ashtable

    cloneprotected native Objectclone() thros Clone!ot"upported#xception

    Creates a new object of the same class as this object. t then initialies each of the new

    object$s fields by assigning it the same value as the corresponding field in this object. /oconstructor is called.

    %he clonemethod of class Objectwill only clone an object whose class indicates that it

    is willing for its instances to be cloned. A class indicates that its instances can be cloned

    by declaring that it implements the Cloneableinterface.

    *eturns)

    a clone of this instance.

    Thros)Clone/ot0upportedE'ceptionif the object$s class does not support the Cloneableinterface. 0ubclasses that override

    the clonemethod can also throw this e'ception to indicate that an instance cannot be

    cloned.

    Thros)OutOf1emoryError

    if there is not enough memory.

    'ee &lso)Cloneable

    to'tringpublic "tringto"tring()

    !eturns a string representation of the object. n general, the to"tringmethod returns a

    string that 2te'tually represents2 this object. %he result should be a concise but

    informative representation that is easy for a person to read. t is recommendedthat allsubclasses override this method.

    %he to"tringmethod for class Objectreturns a string consisting of the name of the

    class of which the object is an instance, the at-sign character 3$$, and the unsigned

    he'adecimal representation of the hash code of the object.

    *eturns)

    http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Boolean.html#hashCode()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Boolean.html#hashCode()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.util.Hashtable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.util.Hashtable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.CloneNotSupportedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.CloneNotSupportedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.CloneNotSupportedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.OutOfMemoryError.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.OutOfMemoryError.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Cloneable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.String.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Boolean.html#hashCode()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.util.Hashtable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.CloneNotSupportedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.CloneNotSupportedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.OutOfMemoryError.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Cloneable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.String.html#_top_
  • 8/12/2019 Object Class Methods in Java

    4/35

    a string representation of the object.

    notifypublic final native void notify()

    "a#es up a single thread that is waiting on this object$s monitor. A thread waits on anobject$s monitor by calling one of the aitmethods.

    %his method should only be called by a thread that is the owner of this object$s monitor.

    A thread becomes the owner of the object$s monitor in one of three ways&

    4y e'ecuting a synchronied instance method of that object.

    4y e'ecuting the body of a synchronizedstatement that synchronies on the

    object.

    +or objects of type Class%by e'ecuting a synchronied static method of that

    class.

    Only one thread at a time can own an object$s monitor.

    Thros)llegal1onitor0tateE'ception

    if the current thread is not the owner of this object$s monitor.

    'ee &lso)

    notifyAll, wait

    notify&llpublic final native void notify&ll()

    "a#es up all threads that are waiting on this object$s monitor. A thread waits on an

    object$s monitor by calling one of the aitmethods.

    %his method should only be called by a thread that is the owner of this object$s monitor.

    0ee the notifymethod for a description of the ways in which a thread can become theowner of a monitor.

    Thros)llegal1onitor0tateE'ception

    if the current thread is not the owner of this object$s monitor.

    'ee &lso)notify, wait

    aitpublic final native void ait(long ti'eout) thros nterrupted#xception

    "aits to be notified by another thread of a change in this object.

    %he current thread must own this object$s monitor. %he thread releases ownership of thismonitor and waits until either of the following two conditions has occurred&

    Another thread notifies threads waiting on this object$s monitor to wa#e up either

    through a call to the notifymethod or the notify&llmethod.

    %he timeout period, specified by the ti'eoutargument in milliseconds, has

    elapsed.

    http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#wait()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_
  • 8/12/2019 Object Class Methods in Java

    5/35

    %he thread then waits until it can re-obtain ownership of the monitor and resumes

    e'ecution.

    %his method should only be called by a thread that is the owner of this object$s monitor.0ee the notifymethod for a description of the ways in which a thread can become the

    owner of a monitor.

    +araeters)

    timeout - the ma'imum time to wait in milliseconds.

    Thros)llegalArgumentE'ception

    if the value of timeout is negative.

    Thros)llegal1onitor0tateE'ceptionif the current thread is not the owner of the object$s monitor.

    Thros)nterruptedE'ception

    if another thread has interrupted this thread.

    'ee &lso)

    notify, notifyAllaitpublic final void ait(long ti'eout% int nanos) thros nterrupted#xception

    "aits to be notified by another thread of a change in this object.

    %his method is similar to the aitmethod of one argument, but it allows finer control

    over the amount of time to wait for a notification before giving up.

    %he current thread must own this object$s monitor. %he thread releases ownership of this

    monitor and waits until either of the following two conditions has occurred&

    Another thread notifies threads waiting on this object$s monitor to wa#e up either

    through a call to the notifymethod or the notify&llmethod.

    %he timeout period, specified by ti'eoutmilliseconds plus nanosnanoseconds

    arguments, has elapsed.

    %he thread then waits until it can re-obtain ownership of the monitor and resumese'ecution

    %his method should only be called by a thread that is the owner of this object$s monitor.

    0ee the notifymethod for a description of the ways in which a thread can become the

    owner of a monitor.

    +araeters)

    timeout - the ma'imum time to wait in milliseconds.

    nano - additional time, in nanoseconds range 5-666666.

    Thros)llegalArgumentE'ception

    if the value of timeout is negative or the value of nanos is not in the range 5-666666.

    Thros)llegal1onitor0tateE'ception

    if the current thread is not the owner of this object$s monitor.

    http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalArgumentException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_
  • 8/12/2019 Object Class Methods in Java

    6/35

    Thros)nterruptedE'ception

    if another thread has interrupted this thread.

    aitpublic final void ait() thros nterrupted#xception

    "aits to be notified by another thread of a change in this object.

    %he current thread must own this object$s monitor. %he thread releases ownership of this

    monitor and waits until another thread notifies threads waiting on this object$s monitor to

    wa#e up either through a call to the notifymethod or the notify&llmethod. %he thread

    then waits until it can re-obtain ownership of the monitor and resumes e'ecution.

    %his method should only be called by a thread that is the owner of this object$s monitor.

    0ee the notifymethod for a description of the ways in which a thread can become the

    owner of a monitor.

    Thros)llegal1onitor0tateE'ception

    if the current thread is not the owner of the object$s monitor.

    Thros)nterruptedE'ceptionif another thread has interrupted this thread.

    'ee &lso)

    notify, notifyAll

    finali%eprotected void finalize() thros hroable

    Called by the garbage collector on an object when garbage collection determines that

    there are no more references to the object. A subclass overrides the finalizemethod to

    dispose of system resources or to perform other cleanup.

    Any e'ception thrown by the finalizemethod causes the finaliation of this object to be

    halted, but is otherwise ignored.

    %he finalizemethod in Objectdoes nothing.

    What,s the difference beteen an application server and a eb server-

    A "eb 0erver understands and supports only *%%7 protocol whereas an Application 0erver

    supports *%%7,%C787 and many more protocols. Also many more features such as

    Caches,Clusters,9oad 4alancing are there in Application 0ervers which are not available in "eb0ervers. "e can also Configure Application 0ervers to wor# as "eb 0erver. n short, Applicaion

    0erver is a super set of which "eb 0erver is a sub set.

    :ou can$t run E4 or any business logic in avawebserver. An application server should have

    the capability to run business logic in it. %hat$s why we can$t say that "server a applicationserver.

    %he "eb server&

    http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Throwable.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.IllegalMonitorStateException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.InterruptedException.html#_top_http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notify()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Object.html#notifyAll()http://www.cis.upenn.edu/~bcpierce/courses/629/jdkdocs/api/java.lang.Throwable.html#_top_
  • 8/12/2019 Object Class Methods in Java

    7/35

    A "eb server handles the *%%7 protocol. "hen the "eb server receives an *%%7 reuest, it

    responds with an *%%7 response, such as sending bac# an *%19 page. %o process a reuest, a

    "eb server may respond with a static *%19 page or image, send a redirect, or delegate thedynamic response generation to some other program such as C; scripts, 07s (ava0erver

    7ages), servlets, A07s (Active 0erver 7ages), server-side ava0cripts, or some other server-side

    technology. "hatever their purpose, such server-side programs generate a response, most oftenin *%19, for viewing in a "eb browser.

  • 8/12/2019 Object Class Methods in Java

    8/35

    Exception Handling

    ? An e'ception is an event, which occurs during the e'ecution of a program, that interrupts the

    normal flow of the program. t is an error thrown by a class or method reporting an error in code.

    ? %he $%hrowable$ class is the superclass of all errors and e'ceptions in the ava language

    ? E'ceptions are broadly classified as chec/ed e"ceptionsand unchec/ed e"ceptions$. &ll

    *untieE"ceptions and Errors are unchec/ed e"ceptions.!est of the e'ceptions are called

    chec#ed e'ceptions. Chec#ed e'ceptions should be handled in the code to avoid compile time

    errors.? E'ceptions can be handled by using $try-catch$ bloc#. %ry bloc# contains the code which is

    under observation for e'ceptions. %he catch bloc# contains the remedy for the e'ception. f any

    e'ception occurs in the try bloc# then the control jumps to catch bloc#.

    ? f a method doesn$t handle the e'ception, then it is mandatory to specify the e'ception type inthe method signature using $throws$ clause.

    ? "e can e'plicitly throw an e'ception using $throw$ clause

    http&88www.java>novice.com8java@interview@uestions8

    0uestion) 1ive the list of Java Object class

    ethods.clone() * Creates and returns a copy of this object.

    equals() * ndicates hether so'e other object is +equal to+ this one.finalize() * Called by the garbage collector on an object hen garbage

    collectiondeter'ines that there are no 'ore references to the

    object.getClass() * ,eturns the runti'e class of an object.

    http://www.java2novice.com/java_interview_questions/http://www.java2novice.com/java_interview_questions/
  • 8/12/2019 Object Class Methods in Java

    9/35

    hashCode() * ,eturns a hash code value for the object.notify() * -aes up a single thread that is aiting on this object/s

    'onitor.notify&ll() * -aes up all threads that are aiting on this object/s

    'onitor.to"tring() * ,eturns a string representation of the object.ait() * Causes current thread to ait until another thread invoes

    the notify() 'ethodor the notify&ll() 'ethod for this object.

    0uestion) Can Java thread object invo/e

    start ethod tice-

    pacage co'.java0novice.ex'pcode1

    public class 2y#x'pCode extends hread3

    public void run()3"yste'.out.println(+,un+)1

    4

    public static void 'ain("tring a56)3hread t7 = ne hread(ne 2y#x'pCode())1t7.start()1t7.start()1

    44!o% it thros llegalhread"tate#xception

    0uestion) Can e call servlet destory(! froservice(!-

    &s you no% destory() is part of servlet life cycle 'ethods% it is used toill the servlet instance. "ervlet #ngine is used to call destory(). n case%if you call destroy 'ethod fro' service()% it just execute the code rittenin the destory()% but it on8t ill the servlet instance. destroy() ill becalled before illing the servlet instance by servlet engine.

    0uestion) Can e override static ethod-

    -e cannot override static 'ethods. "tatic 'ethods are belogs to class% notbelongsto object. nheritance ill not be applicable for class 'e'bers

    0uestion) Can you list seriali%ation ethods-

  • 8/12/2019 Object Class Methods in Java

    10/35

    "erialization interface does not have any 'ethods. t is a 'arer interface.t just tells that your class can be serializable.

    0uestion) What is the difference beteen

    super(! and this(!-super() is used to call super class constructor% hereas this() used to callconstructors in the sa'e class% 'eans to call para'eterized constructors.

    0uestion) 2o to prevent a ethod fro

    being overridden-

    9y specifying final eyord to the 'ethod you can avoid overriding

    in a subcalss. "i'ilarlly one can use final at class level toprevent creating subclasses.

    0uestion) Can e create abstract classes

    ithout any abstract ethods-

    :es% e can create abstract classes ithout any abstract 'ethods.

    0uestion) 2o to destroy the session in

    servlets-

    9y calling invalidate() 'ethod on session object% e can destory the session.

    0uestion) Can e have static ethods in

    interface-

    9y default% all 'ethods in an interface are decleared as public% abstract. t

    ill never be static.

    0uestion) What is transient variable-

    ransient variables cannot be serialized. ;uring serialization process%transient variable states ill not be serialized. "tate of the value illbe alays defaulted after deserialization.

  • 8/12/2019 Object Class Methods in Java

    11/35

    0uestion) 3ncase# there is a return at the end

    of try bloc/# ill e"ecute finally bloc/-

    :es% the finally bloc ill be executed even after riting return state'entat the end fo try bloc. t returns after executing finally bloc.

    0uestion) What is abstract class or abstract

    ethod-

    -e cannot create instance for an abstract class. -e can able to createinstance for its subclass only. 9y specifying abstract eyord just beforeclass% e can 'ae a class as abstract class.

    public abstract class 2y&bstractClass3

    4

    &bstract class 'ay or 'ay not contains abstract 'ethods. &bstract 'ethod isjust 'ethod signature% it does not containes any i'ple'entation. ts subclass'ust provide i'ple'entation for abstract 'ethods. &bstract 'ethods are looslie as given belo ele'ents% if you are inserting at index ?% thenyou need to shift the indexes above ? to one 'ore.

    0uestion) What is daeon thread-

  • 8/12/2019 Object Class Methods in Java

    12/35

    ;ae'on thread is a lo priority thread. t runs inter'ittentlyin the bac ground% and taes care of the garbage collectionoperation for the java runti'e syste'. 9y calling set;ae'on()'ethod is used to create a dae'on thread.

    0uestion) Does each thread in java uses

    seperate stac/-Answer&n @ava every thread 'aintains its on separate stac. t iscalled ,unti'e "tac but they share the sa'e 'e'ory.

    0uestion) What is the difference beteen Enueration and 3terator-

    Answer&he functionality of #nu'eration and the terator are sa'e. :ou can getre'ove()fro' terator to re'ove an ele'ent% hile hile #nu'eration does not havere'ove()'ethod. Asing #nu'eration you can only traverse and fetch the objects% hereas usingterator e can also add and re'ove the objects. "o terator can be useful ifyou antto 'anipulate the list and #nu'eration is for read*only access.

    0uestion) 5ind out belo sitch stateent

    output.

    Code&public static void 'ain("tring a56)3

    int price = B1sitch (price) 3

    case 0< "yste'.out.println(+t is< 0+)1default< "yste'.out.println(+t is< default+)1case ?< "yste'.out.println(+t is< ?+)1case < "yste'.out.println(+t is< +)1

    44

    Answer&t is< defaultt is< ?t is<

    0uestion) Does syste.e"it(! in try bloc/

  • 8/12/2019 Object Class Methods in Java

    13/35

    e"ecutes code in finally bloc/-

    Code&try3

    "yste'.out.println(+ a' in try bloc+)1

    "yste'.exit(7)14 catch(#xception ex)3

    ex.print"tacrace()14 finally 3

    "yste'.out.println(+ a' in finally blocDDD+)14

    Answer&t ill not execute finally bloc. he progra' ill be ter'inatedafter "yste'.exit() state'ent.

    0uestion) What is fail6fast in java-

    & fail*fast syste' is nothing but i''ediately report any failure thatis liely to lead to failure. -hen a proble' occurs% a fail*fast syste'fails i''ediately. n @ava% e can find this behavior ith iterators.ncase% you have called iterator on a collection object% and anotherthread tries to 'odify the collection object% then concurrent 'odificationexception ill be thron. his is called fail*fast.

    0uestion) What is final# finally and finali%e-

    final>)14 catch(#xception ex)3

    44

  • 8/12/2019 Object Class Methods in Java

    18/35

    4

    0uestion) When to use 'tring and

    'tring7uffer-

    -e no that "tring is i''utable object. -e can not change the valueof a "tring object once it is initiated. f e try to change the value ofthe existing "tring object then it creates ne object rather than changingthe value of the existing object. "o incase% e are going to do 'ore'odificatios on "tring% then use "tring9uffer. "tring9uffer updates theexisting objects value% rather creating ne object.

    0uestion) What is difference beteen

    'tring7uffer and 'tring7uilder-

    he only difference beteen "tring9uffer and "tring9uilder is "tring9ufferis thread*safe% that is "tring9uffer is synchronized.

    0uestion) What is rapper class in java-

    #verything in java is an object% except pri'itives. Eri'itives areint% short% long% boolean% etc. "ince they are not objects% they cannotreturn as objects% and collection of objects. o support this% java providesrapper classes to 'ove pri'itives to objects. "o'e of the rapper classesare nteger% ong% 9oolean% etc.

    0uestion) 3s 3terator a Class-

    terator is an interface. t is not a class. t is used toiterate through each and every ele'ent in a list. terator isi'ple'ented terator design pattern.

    0uestion) What is java classpath-

    he classpath is an environ'ent variable. t is used tolet the co'piler no here the class files are availablefor i'port.

    0uestion) Can a class in java be private-

    -e can not declare top level class as private. @ava allosonly public and default 'odifier for top level classes in java.

  • 8/12/2019 Object Class Methods in Java

    19/35

    nner classes can be private.

    0uestion) 3s null a /eyord in java-

    he null value is not a eyord in java. true and flase are also not

    eyords in java. hey are reserved ords in java language.

    0uestion) What is the initial state of a thread

    hen it is started-

    -hen the thread is createdn and started% initially it ill bein the ready state.

    0uestion) What is the super class forE"ception and Error-

    he super class or base class for #xception and #rror is hroable.

    0uestion) What is Class.for8ae(!-

    Class.for!a'e() loads the class into the Classoader.

    0uestion) Can interface be final-!o. -e can not instantiate interfaces% so in order to 'ae interfacesuseful e 'ust create subclasses. he final eyord 'aes a class unableto be extended.

    0uestion) What is the difference beteen

    e"ception and error-

    &n error is an irrecoverable condition occurring at runti'e lie out of'e'ory error. hese ind of jv' errors cannot be handled at runti'e.#xceptions are because of condition failures% hich can be handledeasily at runti'e.

    0uestion) What is default value of a local

    variables-

  • 8/12/2019 Object Class Methods in Java

    20/35

    he local variables are not initialized to any default values. -e shouldnot use local variables ith out initialization. #ven the java co'pilerthros error.

    0uestion) What is local class in java-

    n java% local classes can be defined in a bloc as in a'ethod body or local bloc.

    0uestion) Can e initialise uninitiali%ed final

    variable-

    :es. -e can initialise blan final variable in constructor% only inconstrutor.he condition here is the final variable should be non*static.

    0uestion) Can e declare abstract ethod as

    final-

    !o% e can not declare abstract 'ethod as final. -e have toproved i'ple'entation to abstract 'ethods in subclasses.

    0uestion) Can e have finally bloc/ ithout

    catch bloc/-:es% e can have finally bloc ithout catch bloc.

    0uestion) What is pass by value and pass by

    reference-

    Eass by value< Eassing a copy of the value% not the originalreference.

    Eass by reference< Easssing the address of the object% so that

    you can access the original object.

    0uestion) Can e declare ain ethod as

    private-

    :es% e can declare 'ain 'ethod as private. t co'piles ithout

  • 8/12/2019 Object Class Methods in Java

    21/35

    any errors% but in runti'e% it says 'ain 'ethod is not public.

    0uestion) What is the difference beteen

    preeptive scheduling and tie slicing-

    Preemptive scheduling:he highest priority tas executes until it entersthe aiting or dead states or a higher priority tas co'es into existence.

    Time slicing:& tas executes for a predefined slice of ti'e and thenreenters the pool of ready tass. he scheduler then deter'ines hich tasshould execute next% based on priority and other factors.

    0uestion) Can non6static eber classes

    (4ocal classes! have static ebers-!o% non*static 'e'ber classes cannot have static 'e'bers. 9ecause%an instance of a non*static 'e'ber class or local class 'ust becreated in the context of an instance of the enclosing class. :oucan declare constants% 'eans static final variables.

    0uestion) What are the environent

    variables do e neet to set to run Java-

    -e need to set to environ'ent variables those are E&H and C&""E&H.

    0uestion) Can you seriali%e static fields of a

    class-

    "ince static fields are not part of object state% they are part of class%serialization ignores the static fields.

    0uestion) What is the difference beteen

    declaring a variable and defining a variable-

    When variable declaration we just mention the type of the variable and it's name, it does nothave any reference to live object. But defining means combination of declaration andinitialization. The examples are as given below

    Declaration:

  • 8/12/2019 Object Class Methods in Java

    22/35

    !ist list"Defining:!ist list # new $rray!ist%&"

    0uestion) Where can e use seriali%ation-

    Whenever an object has to sent over the networ, those objects should be serialized. $lso if thestate of an object is to be saved, objects need to be serilazed.

    0uestion) What odifiers are alloed for

    ethods in an 3nterface-

    (nly public and abstract modifiers are allowed for methods in an interfaces.

    0uestion) What is the purpose of *untie

    and 'yste class-

    The purpose of the )untime class is to provide access to the *ava runtime system. The runtimeinformation lie memory availability, invoing the garbage collector, etc.

    The purpose of the +ystem class is to provide access to system resources. t containsaccessibility to standard input, standart output, error output streams, current time in millis,terminating the application, etc.

    0uestion) Which one is faster- &rray4ist or

    9ector- Why-

    $rray!ist is faster than -ector. The reason is synchronization. -ector is synchronized. $s wenow synchronization reduces the performance.

    0uestion) What is the difference beteen

    static synchroni%ed and synchroni%edethods-

    +tatic synchronized methods synchronize on the class object. f one thread is executing a staticsynchronized method, all other threads trying to execute any static synchronized methods willbe bloced.

  • 8/12/2019 Object Class Methods in Java

    23/35

    on/static synchronized methods synchronize on this ie the instance of the class. f one threadis executing a synchronized method, all other threads trying to execute any synchronizedmethods will be bloced.

    0uestion) What is the order of catch bloc/s

    hen catching ore than one e"ception-

    When you are handling multiple catch blocs, mae sure that you are specifing exception subclasses first, then followed by exception super classes. (therwise we will get compile time error.

    0uestion) What is the difference beteen the

    prefi" and postfi" fors of the increent(::!

    operator-The prefix form first performs the increment operation and then returns the value of theincrement operation. The postfix form first returns the current value of the expression and thenperforms the increment operation on that value. 0or example

    int count#1"+ystem.out.println%22count&"

    displays 3. $nd

    int count#1"

    +ystem.out.println%count22&"

    displays 1.

    0uestion) What is hashCode-

    The hashcode of a *ava (bject is simply a number, it is 43/bit signed int, that allows an objectto be managed by a hash/based data structure. We now that hash code is an uni5ue idnumber allocated to an object by *-6. But actually speaing, 7ash code is not an uni5uenumber for an object. f two objects are e5uals then these two objects should return same hash

    code. +o we have to implement hashcode%& method of a class in such way that if two objectsare e5uals, ie compared by e5ual%& method of that class, then those two objects must returnsame hash code. f you are overriding hash8ode you need to override e5uals method also.

    0uestion) What is the difference beteen

    2ashtable and 2ashMap-

  • 8/12/2019 Object Class Methods in Java

    24/35

    The basic differences are 7ashtable is synchronized and 7ash6ap is not synchronized.7ashtable does not allow null values, and 7ash6ap allows null values.

    0uestion) What are the restrictions hen

    overriding a ethod-(verriding methods must have the same name, parameter list, and same return type. i.e., theymust have the exact signature of the method we are going to override, including return type.The overriding method cannot be less visible than the method it overrides. i.e., a public methodcannot be override to private. The overriding method may not throw any exceptions that may notbe thrown by the overridden method.

    0uestion) What is the use of assert /eyord-

    *ava assertion feature allows developer to put assert statements in *ava source code to help

    unit testing and debugging. $ssert eyword validates certain expressions. t replaces the if bloceffectively and throws an $ssertion9rror on failure.

    0uestion) What is adapter class-

    $n adapter class provides the default implementation of all methods in an event listenerinterface. $dapter classes are very useful when you want to process only few of the events thatare handled by a particular event listener interface. :ou can define a new class by extendingone of the adapter classes and implement only those events relevant to you.

    0uestion) What is difference beteen brea/#continue and return stateents-

    The brea statement results in the termination of the loop, it will come out of the loop and stopsfurther iterations. The continue statement stops the current execution of the iteration andproceeds to the next iteration. The return statement taes you out of the method. t stopsexecuting the method and returns from the method execution.

    0uestion) What is the difference beteen

    hile and do6hile stateents-

    The while statement verifies the condition before entering into the loop to see whether the nextloop iteration should occur or not. The do/while statement executes the first iteration withoutchecing the condition, it verifies the condition after finishing each iteration. The do/whilestatement will always execute the body of a loop at least once.

  • 8/12/2019 Object Class Methods in Java

    25/35

    0uestion) When does the copiler provides

    the default constructor-

    The compiler provides a default constructor if no other constructors are available in the class. ncase the class contains parametarized constructors, compiler doesnot provide the defaultconstructor.

    0uestion) What are the advantages of java

    pac/age.

    *ava pacages helps to resolve naming conflicts when different pacages have classes with thesame names. This also helps you organize files within your project. 0or example, java.iopacage do something related to ;( and java.net pacage do something to do with networ and

    so on. f we tend to put all .java files into a single pacage, as the project gets bigger, then itwould become a nightmare to manage all your files.

    0uestion) What is dynaic class loading-

    Bynamic loading is a techniue for programmatically invo#ing the functions of a class loader atrun time. 9et us loo# at how to load classes dynamically by using Class.forName (String

    className);method, it is a static method.

    %he above static method returns the class object associated with the class name. %he string

    class/ame can be supplied dynamically at run time. Once the class is dynamically loaded theclass.newInstance ()method returns an instance of the loaded class. t is just li#e creating a class

    object with no arguments.

    A ClassNotFoundExceptionis thrown when an application tries to load in a class through its

    class name, but no definition for the class with the specified name could be found.

    0uestion) What happens if you do not

    provide a constructor-

    *ava does not actually re5uire an explicit constructor in the class description. f you do notinclude a constructor, the *ava compiler will create a default constructor in the byte code with anempty argument.

  • 8/12/2019 Object Class Methods in Java

    26/35

    0uestion) Difference beteen shallo cloning

    and deep cloning of objects-

    %he default behavior of an objects clone() method automatically yields a shallow copy. 0o toachieve a deep copy the classes must be edited or adjusted.

    Shallow copy;enerally clone method of an object, creates a new instance of the same class andcopies all the fields to the new instance and returns it. %his is called shallow copy. Object class

    provides a clone method and provides support for the shallow copy. t returns DObject as type

    and you need to e'plicitly cast bac# to your original object. 0ince the Object class has the clonemethod, you cannot use it in all your classes. %he class which you want to be cloned should

    implement clone method and overwrite it. t should provide its own meaning for copy or to the

    least it should invo#e the super.clone(). Also you have to implement Cloneable mar#er interface

    or else you will get Clone/ot0upportedE'ception. "hen you invo#e the super.clone() then you

    are dependent on the Object classs implementation and what you get is a shallow copy.

    !eep copy"hen you need a deep copy then you need to implement it yourself. "hen the copied

    object contains some other object its references are copied recursively in deep copy. "hen you

    implement deep copy be careful as you might fall for cyclic dependencies. f you dont want toimplement deep copy yourselves then you can go for serialiation. t does implements deep copy

    implicitly and gracefully handling cyclic dependencies.

    0uestion) Can e have interfaces ith no

    defined ethods in java-%he interfaces with no defined methods act li#e mar#ers. %hey just tell the compiler that theobjects of the classes implementing the interfaces with no defined methods need to be treated

    differently. 1ar#er interfaces are also #nown as tagF interfaces.

    0uestion) What is the difference beteen

    ;

  • 8/12/2019 Object Class Methods in Java

    27/35

    f euals() method does not e'ist in a user supplied class then the inherited Object class$s

    euals() method will be called which evaluates if the references point to the same object in

    memory. n this case, the object.euals() wor#s just li#e the 2GG2 operator.

    0uestion) 2o can you create an iutable

    class in java-

    *ere are the steps to create immutable class&

    Beclare the class as final, we can not e'tend the final class.

    public final class MyTestImmutable { ... }

    Beclare all fields as final. +inal fields can not be changed once its assigned.

    private final int salary;

    Bo not provide any method which can change the state of the object, for e'ample the settermethods which changes the values of the instance variables.

    %he thisF reference is not allowed to escape during construction from the immutable class and

    the immutable class should have e'clusive access to fields that contain references to mutable

    objects li#e arrays, collections and mutable classes li#e Bate etc by&

    Beclaring the mutable references as private./ot returning or e'posing the mutable references to the caller.

    0uestion) What are access odifiers in java-

    pu"lic A class or interface may be accessed from outside the pac#age. Constructors, inner

    classes, methods and field variables may be accessed wherever their class is accessed.

    protected Accessed by other classes in the same pac#age or any subclasses of same pac#age or

    different pac#age.

    pri#ate Accessed only within the class in which they are declared.

    no modifier (default modifier) Accessed only with in the class.

    0uestion) Can e have private constructor in

  • 8/12/2019 Object Class Methods in Java

    28/35

    java-

    7rivate constructor is used if you do not want other classes to instantiate the object.

    7rivate constructors are used in singleton design pattern, factory method design pattern.

    0uestion) Why do e need generics in java-

    Code that uses generics has many benefits over non-generic code&

    >! 'tronger type chec/s at copile tie)A ava compiler applies strong type chec#ing togeneric code and issues errors if the code violates type safety. +i'ing compile-time errors is

    easier than fi'ing runtime errors, which can be difficult to find.

    ?! Eliination of casts)f you use generics, then e'plicit type casting is not reuired.

    @! Enabling prograers to ipleent generic algoriths)4y using generics, programmers

    can implement generic algorithms that wor# on collections of different types, can be customied,and are type safe and easier to read.

    http&88www.tutorialspoint.com8java8java@[email protected]

    ava is an Object-Oriented 9anguage. As a language that has the Object Oriented feature, ava

    supports the following fundamental concepts&

    7olymorphism

    nheritance

    Encapsulation

    Abstraction

    Classes

    Objects

    nstance

    http://www.tutorialspoint.com/java/java_object_classes.htmhttp://www.tutorialspoint.com/java/java_object_classes.htm
  • 8/12/2019 Object Class Methods in Java

    29/35

    1ethod

    1essage 7arsing

    n this chapter, we will loo# into the concepts Classes and Objects.

    Object 6Objects have states and behaviors. E'ample& A dog has states - color, name,

    breed as well as behaviors -wagging, bar#ing, eating. An object is an instance of a class.

    Class 6A class can be defined as a template8blue print that describes the behaviors8states

    that object of its type support.

    Objects in Java)

    9et us now loo# deep into what are objects. f we consider the real-world we can find many

    objects around us, Cars, Bogs, *umans, etc. All these objects have a state and behavior.

    f we consider a dog, then its state is - name, breed, color, and the behavior is - bar#ing,wagging, running

    f you compare the software object with a real world object, they have very similar

    characteristics.

    0oftware objects also have a state and behavior. A software object$s state is stored in fields and

    behavior is shown via methods.

    0o in software development, methods operate on the internal state of an object and the object-to-object communication is done via methods.

    Classes in Java)

    A class is a blue print from which individual objects are created.

    A sample of a class is given below&

    public class ;og3 "tring breed1 int age1 "tring color1

    void baring()3 4

    void hungry()3 4

    void sleeping()3 44

  • 8/12/2019 Object Class Methods in Java

    30/35

    A class can contain any of the following variable types.

    4ocal variables) Hariables defined inside methods, constructors or bloc#s are called

    local variables. %he variable will be declared and initialied within the method and thevariable will be destroyed when the method has completed.

    3nstance variables) nstance variables are variables within a class but outside anymethod. %hese variables are instantiated when the class is loaded. nstance variables can

    be accessed from inside any method, constructor or bloc#s of that particular class.

    Class variables) Class variables are variables declared with in a class, outside any

    method, with the static #eyword.

    A class can have any number of methods to access the value of various #inds of methods. n theabove e'ample, bar#ing(), hungry() and sleeping() are methods.

    4elow mentioned are some of the important topics that need to be discussed when loo#ing into

    classes of the ava 9anguage.

    Constructors)

    "hen discussing about classes, one of the most important sub topic would be constructors. Every

    class has a constructor. f we do not e'plicitly write a constructor for a class the ava compiler

    builds a default constructor for that class.

    Each time a new object is created, at least one constructor will be invo#ed. %he main rule ofconstructors is that they should have the same name as the class. A class can have more than one

    constructor.

    E'ample of a constructor is given below&

    public class Euppy3 public Euppy()3 4

    public Euppy("tring na'e)3 GG his constructor has one para'eter% name. 44

    ava also supports 0ingleton Classeswhere you would be able to create only one instance of a

    class.

    Creating an Object)

    As mentioned previously, a class provides the blueprints for objects. 0o basically an object is

    created from a class. n ava, the new #ey word is used to create new objects.

    http://www.tutorialspoint.com/java/java_using_singleton.htmhttp://www.tutorialspoint.com/java/java_using_singleton.htmhttp://www.tutorialspoint.com/java/java_using_singleton.htm
  • 8/12/2019 Object Class Methods in Java

    31/35

    %here are three steps when creating an object from a class&

    Declaration) A variable declaration with a variable name with an object type.

    3nstantiation) %he $new$ #ey word is used to create the object.

    3nitiali%ation) %he $new$ #eyword is followed by a call to a constructor. %his call

    initialies the new object.

    E'ample of creating an object is given below&

    public class Euppy3

    public Euppy("tring na'e)3 GG his constructor has one para'eter% name. "yste'.out.println(+Eassed !a'e is

  • 8/12/2019 Object Class Methods in Java

    32/35

    "yste'.out.println(+Eassed !a'e is

  • 8/12/2019 Object Class Methods in Java

    33/35

    mport and pac#age statements will imply to all the classes present in the source file. t is

    not possible to declare different import and8or pac#age statements to different classes in

    the source file.

    Classes have several access levels and there are different types of classes abstract classes, final

    classes, etc. will be e'plaining about all these in the access modifiers chapter.

    Apart from the above mentioned types of classes, ava also has some special classes called nner

    classes and Anonymous classes.

    Java +ac/age)

    n simple, it is a way of categoriing the classes and interfaces. "hen developing applications in

    ava, hundreds of classes and interfaces will be written, therefore categoriing these classes is a

    must as well as ma#es life much easier.

    3port stateents)

    n ava if a fully ualified name, which includes the pac#age and the class name, is given then

    the compiler can easily locate the source code or classes. mport statement is a way of giving the

    proper location for the compiler to find that particular class.

    +or e'ample, the following line would as# compiler to load all the classes available in directory

    java@installation8java8io &

    i'port java.io.M1

    & 'iple Case 'tudy)

    +or our case study, we will be creating two classes. %hey are Employee and Employee%est.

    +irst open notepad and add the following code. !emember this is the Employee class and the

    class is a public class. /ow, save this source file with the name Employee.java.

    %he Employee class has four instance variables name, age, designation and salary. %he class hasone e'plicitly defined constructor, which ta#es a parameter.

    i'port java.io.M1public class #'ployee3 "tring na'e1 int age1 "tring designation1 double salary1

    GG his is the constructor of the class #'ployee public #'ployee("tring na'e)3 this.na'e = na'e1

  • 8/12/2019 Object Class Methods in Java

    34/35

    4 GG &ssign the age of the #'ployee to the variable age. public void e'p&ge(int e'p&ge)3 age = e'p&ge1 4 GM &ssign the designation to the variable designation.MG public void e'p;esignation("tring e'p;esig)3 designation = e'p;esig1 4 GM &ssign the salary to the variable salary.MG public void e'p"alary(double e'p"alary)3 salary = e'p"alary1 4 GM Erint the #'ployee details MG public void print#'ployee()3 "yste'.out.println(+!a'e

  • 8/12/2019 Object Class Methods in Java

    35/35

    C .>!a'e