1 / 49

OOPs

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 ; /**

Télécharger la présentation

OOPs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. OOPs

  2. Coverage • Classes • Object • Overloading • Inheritance • Pass by reference and by value • Interface • Overriding • Abstract • Access specifier

  3. Creating Class and object in java /** Description of the class */ class classNm1{ //describe the variable access_specvarNm; /** describe the constructor */ access_spec classNm1(){ varNm = 0; } /** deiscribe the function @param1 holds the value of rollno of the student @param2 holds………. */ access_specreturn_typemethodNm(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); } }

  4. Overloading More than one methods or constructor having same name with different no. of parameter,types of parameters.

  5. Inheritance • Multiple inheritance not supported by java • To inherit use the keyword extends • Public classNm extends parentClass

  6. Single public class A {  int i=0;  void doSomething () {    i = 5;  }}class B extends A {  int j = 0;  void doSomethingMore () {    j = 10;     i += j;  }}

  7. class C extends B{  int k;   void doEvenMore ();     doSomething ();    doSomethingMore (); }

  8. Pass by reference or value • Pass by value – any primitive value • Reference – object to be passed

  9. Access Specifier • Java provides for 4 access modifiers : • public - access by any other class anywhere. public intpublicVariable; 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.

  10. 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.

  11. A P1 P2 C B F P3 E D

  12. 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

  13. 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

  14. Others • Native – code outside JVM • Transient – object written to file. • Synchronised – used in thread based programs. • Volatile – simultaneously modified by many thread.

  15. Using & executing Example : package xyz.student; public class studentDet{ public static void main(String[])….. } USING : import xyz.student.studentDet; OR import xyz.student.*; EXECUTING : • javac pack2\derivedOtherclass.java • java pack2.derivedOtherclass • SET CLASSPATH = %CLASSPATH%;DIRNAME\xys\student;

  16. 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; } }

  17. abstract class Shape { abstractintgetArea(); } • If 1 or > abstract methods exists exists in a class,then the class also also has to be declared as abstract • No objects can be created. • Cannot declare abstract constructors,abstract static methods. • Either implement all the methods or declare the class itself as abstract.

  18. Object class and Functions

  19. Animal -> cat,dog,horse. Variable -> petType of Animal Type Class objectType = pet.getClass(); s.o.pln(objectType.getName()); o/p dog

  20. String class and Functions • campareTo--- returns a int val -ive if str1 < str2 0 if str1= str2 +ive if str > str2

  21. Casting objects • InstanceOf---- if(obj instanceOf class) • If(obj.getClass() == classnm.class) • If(obj.getClass().getName().equalsEgnoreCase(“classnm”));

  22. 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.

  23. example interface Counting{abstract void increment();abstract int getValue();} class ScoreCounter implements Counting {....}

  24. 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 { intnumWheels = 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 • { intnumWheels = 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.

  25. 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.

  26. 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(); }

  27. Exception Object Throwable Error Exception

  28. Error • Not supposed to handle • Eg. threadDeath,linkageError,VirtualMachineError

  29. Runtime exception • Eg. IndexOutOfbounds,NullPointerException,ArithmeticException,NegativeArraySizeException,IlegalParameterException.

  30. Handling try{ Statements; } catch(Exception e){ s.o.pln(“error is : ” + e.getMessage()); } Finally{ statements; }

  31. Nested try Try{ statements; try{ statement; catch(ArithmeticException ea){ statements; } } Catch(exception e){ }

  32. 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 Throwableconstructors and theThrowableargumenttoinitCause.

  33. User defined • Throw • throws

  34. chained try {} catch (IOException e) {throw new TestException("Other IOException", e);}

  35. Streams

  36. Types • Byte • Character

  37. Byte Streams - classes • InputStream • OutputStream Abstract

  38. InputStream SequenceInputStream FileInputStream ByteArrayInputStream ObjectInputStream FilterInputStream PipedInputStream DataInputStream BufferedInputStream PushBackDataInputStream

  39. Reader and Writer for unicode Reader InputStreamReader BufferedReader CharArrayReader FilterReader StringReader PipedReader

  40. Threads

  41. Threads • Extend thread class • Implement runnable interface

  42. 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.

  43. 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.

  44. Synchronization • synchronized methods public synchronized void run() { SynchronizedOutput.displayList(getName(), msg); } • synchronized blocks synchronized (<object reference expression>) {<code block>}

  45. 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.

  46. Java.lang • Boolean • Character • Class • ClassLoader • Double • Float • Integer • Long • Math • Number • Object • Process • Runtime • SecurityManager • String • StringBuffer • System • Thread • ThreadGroup • Throwable

  47. Java.util • Date • Hashtable • Random • Stack • StringTokenizer • Vector • Collection- arraylist,linkedlist • bitset

  48. Sequence or list object object Object link Object link FIFO object object

More Related