Download OOP

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
OOPs
Coverage
•
•
•
•
•
•
•
•
•
Classes
Object
Overloading
Inheritance
Pass by reference and by value
Interface
Overriding
Abstract
Access specifier
Creating Class and object in java
/**
Description of the class
*/
class classNm1{
//describe the variable
access_spec varNm;
/**
describe the constructor
*/
access_spec classNm1(){
varNm = 0;
}
/**
deiscribe the function
@param1 holds the value of rollno of the student
@param2 holds……….
*/
access_spec return_type methodNm(type param1, type param2..){
Statements;
}
}
class classNm2{
public staic void main(String[] args){
access_spec varNm1;
access_spec varNm2;
classNm1 objectNm = new classNm1();
objectNm.methodNm(varNm1,varNm2);
}
}
Overloading
More than one methods or constructor having same name with different no.
of parameter,types of parameters.
Inheritance
• Multiple inheritance not supported by java
• To inherit use the keyword extends
• Public classNm extends parentClass
Single
public class A
{
int i=0;
void doSomething () {
i = 5;
}
}
class B extends A
{
int j = 0;
void doSomethingMore () {
j = 10;
i += j;
}
}
•
class C extends B
{
int k;
void doEvenMore ();
doSomething ();
doSomethingMore ();
}
Pass by reference or value
• Pass by value – any primitive value
• Reference – object to be passed
Access Specifier
• Java provides for 4 access modifiers :
• public - access by any other class anywhere.
public int publicVariable;
public void publicMethod();
• protected - accessible by the package classes and any
subclasses that are in other packages .
• Default - (also known as "package private“/friendly)
accessible to classes in the same package but not by classes
in other packages, even if these are subclasses.
• private - accessible only within the class. Even methods in
subclasses in the same package do not have access.
• Note that a java file can have only one public class.
Packages
• A package is the Java version of a library.
• A package refers simply to a group of related class files in the same
directory and having in each class file a package directive with that
directory name at the top of the file.
• At the top of each file we put the statement
• package mypack;
• if you do not put your class into a package, it is placed into the
"default unnamed package".
• If you DO NOT USE : any other class in the unnamed package has
access to your class's fields and methods that are not set to private.
P1
A
P2
C
B
F
P3
E
D
Access
Specifiers
Class A
Class B
Class C
Class D
Class E
Class F
Public
Yes
yes
Yes
Yes
Yes
Yes
private
Yes
no
No
No
No
No
protected
Yes
Yes
Yes
No
Yes
Yes
default
yes
Yes
No
No
no
yes
Modifiers -Final
FINAL VARIBLES
• The final modifier indicates that a data field cannot be modified: final double PI = 3.14;
• Any attempt to assigne PI to a new value will result in a runtime error.
• To use them in other class declare them as static
•
public class MyMath
{
public final static double TWO_PI = 6.28;
...
}
•
double y = theta / MyMath.TWO_PI;
FINAL METHOD
• they cannot be overriden by subclasses.
eg : public final double MyFormula()
FINAL CLASS
• Restricts inheritance/subclassing
Modifier-Static
•
•
•
•
Shared variable and methods of a class
Access by classname.staticVariable
Called as class variables and class methods
Cannot access an non-static variable from a static method as they are
instance variables
Others
• Native – code outside JVM
• Transient – object written to file.
• Synchronised – used in thread based
programs.
• Volatile – simultaneously modified by many
thread.
Using & executing
Example :
package xyz.student;
public class studentDet{
public static void main(String[])…..
}
USING : import xyz.student.studentDet;
OR
import xyz.student.*;
EXECUTING :
1. javac pack2\derivedOtherclass.java
2. java pack2.derivedOtherclass
3. SET CLASSPATH = %CLASSPATH%;DIRNAME\xys\student;
Abstract Class
public class Shape {
double getArea ()
{ return 0.0;}
}
public class Rectangle extends Shape {
double ht = 0.0;
double wd = 0.0;
public double getArea ()
{
return (ht*wd);
}
public void setHeight(double ht)
{ this.ht = ht; }
public void setWidth (double wd)
{ this.wd = wd; }
}
public class Circle extends Shape {
double r = 0.0;
public double getArea ()
{ return (3.14 * r * r); }
public void setRadius (double r)
{ this.r = r; }
}
abstract class Shape {
abstract int getArea();
}
1. If 1 or > abstract methods exists exists in a
class,then the class also also has to be
declared as abstract
2. No objects can be created.
3. Cannot declare abstract constructors,abstract
static methods.
4. Either implement all the methods or declare
the class itself as abstract.
Object class and Functions
Method(Public)
Purpose
toString()
Returns the string object eg:
nameOfClass@hexadecimal
Obj1.Equals(obj2)
Data members must be same
getClass()
Returns the class of the current obj
hashCode()
Calculates the hashcode value of the
obj,used to store in hashtables. Details in
java.util
Notify()
Wake a thread associated with a thread
Notifyalll()
Wake all the threads
Wait()
Asks the thread to wait for changes in obj.
(Protected)
Clone()
Creates a copy of the obj
Finalize()
Called when the obj is destroyed
Animal -> cat,dog,horse.
Variable -> petType of Animal Type
Class objectType = pet.getClass();
s.o.pln(objectType.getName());
o/p dog
String class and Functions
• campareTo--- returns a int val
-ive if str1 < str2
0 if str1= str2
+ive if str > str2
•
•
•
•
Casting objects
InstanceOf---- if(obj instanceOf class)
If(obj.getClass() == classnm.class)
If(obj.getClass().getName().equalsEgnoreCase(
“classnm”));
Interface
• A class may implement one or more interfaces.
• a class implementing that interface will need to provide the
methods specified by the interface
• The methods of an interface are abstract.
• All methods of an interface must be public,abstract.
• An interface can also have fields declared as final and static (in
other words constants).
• the method specifications of the interface must match in class,
it will also provide bodies.
• Interface is declared public,protected,default so that it can be
accessed from any class.
example
interface Counting
{
abstract void increment();
abstract int getValue();
}
class ScoreCounter implements Counting {
....
}
• To actually use this interface you create a class that includes a public
double calculateTariff() method and declare that the class implements
Import. For instance here's one such class:
• public class Car extends MotorVehicle implements Import { int
numWheels = 4;
• public double calculateTariff() {
• return this.price * 0.1; }
• }
• One of the advantages of interfaces over classes is that a single class may
implement more than one interface. For example, this Car class
implements three interfaces: Import, Serializable, and Cloneable
• import java.io.*;
• public class Car extends MotorVehicle implements Import, Serializable,
Cloneable
• { int numWheels = 4;
• public double calculateTariff() {
• return this.price * 0.1; }
• }
• Serializable and Cloneable are marker interfaces from the class library that
only add a type to a class, but do not declare any additional methods.
Implementing the Cloneable Interface
•
•
The java.lang.Object class contains a clone() method that returns a bitwise copy of
the current object.
protected native Object clone() throws CloneNotSupportedException
Not all objects are cloneable. It particular only instances of classes that implement
the Cloneable interface can be cloned. Trying to clone an object that does not
implement the Cloneable interface throws a CloneNotSupportedException.
For example, to make the Car class cloneable, you simply declare that it
implements the Cloneable interface. Since this is only a marker interface, you do
not need to add any methods to the class.
public class Car extends MotorVehicle implements Cloneable { // ... }
•
•
•
For example
Car c1 = new Car("New York A12 345", 150.0);
Car c2 = (Car) c1.clone();
•
Most classes in the class library do not implement Cloneable so their instances are
not cloneable.
Most of the time, clones are shallow copies. In other words if the object being
cloned contains a reference to another object A, then the clone contains a
reference to the same object A, not to a clone of A. If this isn't the behavior you
want, you can override clone() yourself.
•
•
•
•
Uncloning derived class
• You may also override clone() if you want to make a subclass
uncloneable, when one of its superclasses does implement
Cloneable. In this case simply use a clone() method that throws a
CloneNotSupportedException. For example,
• public Object clone() throws CloneNotSupportedException {
• throw new CloneNotSupportedException("Can't clone a SlowCar");
• }
• You may also want to override clone() to make it public instead of
protected. In this case, you can simply fall back on the superclass
implementation.
• For example,
• public Object clone() throws CloneNotSupportedException {
• return super.clone(); }
Exception
Object
Throwable
Error
Exception
Error
• Not supposed to handle
• Eg.
threadDeath,linkageError,VirtualMachineError
Runtime exception
• Eg.
IndexOutOfbounds,NullPointerException,Arith
meticException,NegativeArraySizeException,Il
egalParameterException.
Handling
try{
Statements;
}
catch(Exception e){
s.o.pln(“error is : ” + e.getMessage());
}
Finally{
statements;
}
Nested try
Try{
statements;
try{
statement;
catch(ArithmeticException ea){
statements;
}
}
Catch(exception e){
}
The methods of the Throwable class
are:
• toString() Returns the exception followed by a
message string (if one exit) .
• getMessage() Returns the message string of the
Throwable object.
• printStackTrace() Returns the full name of the
exception class and some additional information apart
from the information of first two method.
• getCause() Returns the exception that caused the
occurrence of current exception.
• initCause() Returns the current exception due to the
Throwable constructors and the Throwable argument
to initCause.
User defined
• Throw
• throws
chained
try {
} catch (IOException e) {
throw new TestException("Other
IOException", e);
}
Streams
Types
• Byte
• Character
Byte Streams - classes
• InputStream
• OutputStream
Abstract
InputStream
SequenceInputStream
ObjectInputStream
ByteArrayInputStream
PipedInputStream
FileInputStream
FilterInputStream
DataInputStream
BufferedInputStream
PushBackDataInputStream
Reader and Writer for unicode
Reader
BufferedReader
StringReader
CharArrayReader
PipedReader
InputStreamReader
FilterReader
Threads
Threads
• Extend thread class
• Implement runnable interface
The procedure for creating threads :
• A class implements the Runnable interface, providing
the run() method that will be executed by the thread.
An object of this class is a Runnable object.
• An object of Thread class is created by passing a
Runnable object as argument to the Thread
constructor. The Thread object now has a Runnable
object that implements the run() method.
• The start() method is invoked on the Thread object
created in the previous step. The start() method
returns immediately after a thread has been spawned.
• The thread ends when the run() method ends, either
by normal completion or by throwing an uncaught
exception.
Extending Thread Class
• A class extending the Thread class overrides
the run() method from the Thread class to
define the code executed by the thread.
• This subclass may call a Thread constructor
explicitly in its constructors to initialize the
thread, using the super() call.
• The start() method inherited from the Thread
class is invoked on the object of the class to
make the thread eligible for running.
Synchronization
• synchronized methods
public synchronized void run() {
SynchronizedOutput.displayList(getName(),
msg); }
• synchronized blocks
synchronized (<object reference expression>) {
<code block>
}
Avoid Deadlock
• Keep blocks short - Synchronized blocks
should be short.
• Don't block - Don't ever call a method that
might block, such as InputStream.read(),inside
a synchronized block or method.
• Don't invoke methods on other objects while
holding a lock.
Java.lang
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
Boolean
Character
Class
ClassLoader
Double
Float
Integer
Long
Math
Number
Object
Process
Runtime
SecurityManager
String
StringBuffer
System
Thread
ThreadGroup
Throwable
Java.util
•
•
•
•
•
•
•
•
Date
Hashtable
Random
Stack
StringTokenizer
Vector
Collection- arraylist,linkedlist
bitset
Sequence or list
object
FIFO
object
Object
Object
link
link
object
object