OOPs.

Slides:



Advertisements
Similar presentations
Lecture 5: Interfaces.
Advertisements

Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Tirgul 1 Today’s subject - Java reminders and additions: –Inner classes –Packages –I/O streams –Command Line Arguments –Primitive and Reference Data Types.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Chapter 7: Cloning and RTTI
OOP: Encapsulation &Abstraction
JAVA MULTIPLE CHOICE QUESTION.
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
University of Central Florida COP 3330 Object Oriented Programming
I/O Basics.
Multithreading in Java
Computer Science II Exam 1 Review.
Chapter 9 Inheritance and Polymorphism
Lecture 4: Interface Design
null, true, and false are also reserved.
Extending Classes.
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Interfaces.
Chapter 8 Class Inheritance and Interfaces
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Chap 2. Identifiers, Keywords, and Types
Chapter 11 Inheritance and Encapsulation and Polymorphism
Presentation 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.

A P1 P2 C B F P3 E D Access Specifiers Class A Class B Class C Class D Class E Class F Public Yes yes private no No protected default

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 : javac pack2\derivedOtherclass.java java pack2.derivedOtherclass 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(); } 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.

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 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; 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, return super.clone(); }

Exception Object Throwable Error Exception

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

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

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

Nested try Try{ statements; try{ statement; catch(ArithmeticException ea){ } 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 FileInputStream ByteArrayInputStream ObjectInputStream FilterInputStream PipedInputStream DataInputStream BufferedInputStream PushBackDataInputStream

Reader and Writer for unicode InputStreamReader BufferedReader CharArrayReader FilterReader StringReader PipedReader

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 object Object link Object link FIFO object