Oop Concepts & Abstract Class ,Inheritance

download Oop Concepts & Abstract Class ,Inheritance

of 50

Transcript of Oop Concepts & Abstract Class ,Inheritance

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    1/50

    Day2

    Java Essentials

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    2/50

    2

    Primitive Data Types in Java

    Java Programming language is strongly typed All variables must be first declared before they can be used

    Byte: 8 bit signed integer. Values minimum (-128) tomax 127(inclusive)

    Short: 16 bit signed integer. Values min- (-32,768)to 32767(inclusive)Int: 32 bit signed integer. Values minimum- (-2,147,483,648 ) to (2,147,483,647 )Long:64 bit signed integer

    Float: 32 bit(3.4e-038 to 3.4e+038)Double:64 bitChar:16 bit Unicode character Boolean can only take true or false

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    3/50

    3

    Scope

    Local Scope: Variable will not be available outside itsscopepublic static void main(String args[])

    { int x;if(x==10){ int y = 20;

    System.out.println(x is + x+y is + y);

    }System.out.println(y is +y);

    //error }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    4/50

    4

    Scope Error

    public static void main(String args[]){int bar =1;{

    int bar =2;

    }

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    5/50

    5

    Type Casting

    Automatic Type Conversions Two types are compatible Destination type is larger than source type This type of conversion is called widening

    conversion

    Casting Incompatible Typesint a;byte b;b = (byte) a;

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    6/50

    6

    Type Casting

    Truncation Conversionint i;double d = 1.23;i = (integer)d;

    Automatic Type Promotion

    byte b = 5 0;b = b*2;

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    7/50

    7

    Classes and objects

    A class creates a new data type that can beused to create objects. Act as a blueprintA class is a logical constructObject is nothing but an instance of the classAn object has physical reality i.e. it occupiesspace in memory

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    8/50

    8

    Declaring Objects

    Class-var = new classname();Classname followed by parentheses specifiesthe constructor for the classA constructor defines what occurs when anobject of a class is created

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    9/50

    9

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    10/50

    10

    Introducing methods

    Although it is perfectly fine to create a class that onlycontains data, rarely happensMost of the time methods to access the instancevariables defined by classWhat if another part of the program want volume?

    Type name (parameter-list){body of method

    }Type specifies the type of data returned. Can be any valid

    type.return value;

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    11/50

    11

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    12/50

    12

    Method that takes parameter

    Adding a Method That Takes Parametersint square(){Return 10*10

    }

    Int square(int i){return i*I;}

    Int x = square( 5 );

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    13/50

    13

    Method that takes parameter

    Parameter is a variable defined by a methodthat receives a value when method is called

    An argument is a value that is passed to amethod when it is invoked

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    14/50

    14

    Method that takes parameter

    Can use a parameterized method to improve Box classIn previous example

    mybox1.width=10; etc

    Code is clumsy and error proneNever a good idea to access variables directlyVoid setDim(double w, double h, double d){Width = w; height = h; depth = d;

    mybox1.setDim(10, 20, 5 );Vol=mybox1.volume();

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    15/50

    15

    Constructors

    It can be tedious to initialize all of the variablesin a class each time an instance is createdEven setDim is not rightA constructor initializes an object immediatelyupon creationIt has the same name as the class in which it

    resides and is syntactically similar to methodOnce defined, constructor is automaticallycalled immediately after the object is created,before new operator completes

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    16/50

    16

    Constructors

    Constructors do not have any return type, noteven voidImplicit return type of a class constructor isthe class type itself Creating an instance will have fully initializedusable object immediately

    Rework Box example so that dimensions areautomatically initializedReplace setDim with a constructor

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    17/50

    17

    Constructors

    Box2(){System.out.println("Constructing Box");width = 10;height = 10;depth = 10;}

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    18/50

    18

    Parameterized Constructors

    In the previous example it is not very useful

    So add parameters to constructor

    Box(double w, double h, double d){Width=w; height=h;

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    19/50

    19

    The this keyword

    Sometimes the method will need to refer to theobject that invoked itTo allow this java, java defines the thiskeywordthis can be used inside any method to refer to the current objectIs always a reference to the object on whichmethod was invoked

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    20/50

    20

    Instance Variable Hiding

    Illegal in java to declare to declare two localvariables with same name inside the same or enclosing space

    Box(double width, double height, doubledepth){this.width=width;this.height=height;this.depth=depth}

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    21/50

    21

    Overloading methods

    In java it is possible to define two or moremethods within the same class that share thesame name as long as different parameter

    declarationThis is called method overloadingOne of the ways java implementspolymorphism

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    22/50

    22

    Overloading methods

    One way java implements polymorphism i.e. oneinterface, multiple methodsIn languages that do not support method overloading,each method has unique nameIn C, abs() absolute value of integer labs() absolute value of a long integer fabs() absolute value of a floating point value

    In java standard, abs method is overloaded to handleall numeric typesLeft to the compiler to chose right version

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    23/50

    23

    Argument Passing

    Call-by-value: Copies value of an argument into formalparameters. Therefore changes made to parameter of the subroutine have no effects on the argument usedto call.

    Call-by-reference: A reference to argument, not valueis passed. Changes made to parameter will changeargument

    When a simple type is passed , it is done by use of callby value. Objects are passed by use of call-by-reference

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    24/50

    24

    Inheritance

    Very important component of object-orientedprogramming as allows hierarchicalclassifications

    Each class can use things that are unique to itAnimal (Age, sex, weight) Mammal (Gestationperiod, etc) Canine (Hunting Skills, tail length)

    Dogs (trained, indoor/outdoor) Labrador

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    25/50

    25

    Inheritance

    Enables you to create more specific classesEnables software reuseParent class is called superclassChild class is called subclass

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    26/50

    26

    Inheritance Example

    Class A{ int i; int j;

    showij(){System.out.println(I and j:+ i+ + j);}

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    27/50

    27

    Inheritance Example

    Class B extends A{int k;void showk();

    { System.out.println(k);}

    void sum(){

    system.out.println(i+j+k);}

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    28/50

    28

    Inheritance Example

    Class SimpleInheritance{Public static void main(String args[]}A superObj = new A();B subObj = new B();

    superObj.i = 10;superObj.j = 20;

    superObj.showij();subObj.i = 7; subObj.i = 8; subObj.k = 9 ;subObj.showij(); subObj.showk();

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    29/50

    29

    Inheritance

    We can use a super class directlyUnlike C, Java does not support theinheritance of multiple classes into a single

    sub classAlthough a subclass includes all of themembers of its super class, cannot accessprivate members

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    30/50

    30

    Cannot Access Private Data

    Class A{ int i;

    private int j;setij(int x, int y){i=x; j=y;

    }

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    31/50

    31

    Error Accessing Private Data

    Class B extends A{ int total;

    void sum(){ total = i+j}

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    32/50

    32

    Super class variable can Refrencesub class variableWhen a reference to a subclass object is

    assigned to a superclass reference variable,only access to those parts which are defined in

    superclass

    Boxweight weightbox = new Boxweight(3, 5 ,7, 9 );Box plainbox = new Box();.plainbox = weightbox;

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    33/50

    33

    Super class variable can Refrencesub class variable{ Car x;

    Ford escort;x = escort;

    // but cannot access ford specific features cozthe parent class does not know about them

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    34/50

    34

    Using super

    Classes derived from box were notimplemented as efficiently and robustly.Duplicate in superclass, inefficient

    Also subclass must be granted access tothese membersBut usually superclass keeps details of itsimplementations to itself i.e. encapsulationJava provides a solution to this with keywordsuper

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    35/50

    35

    Using super

    A subclass can call a constructor methoddefined by its superclass by use of followingform

    super(parameter-list);Parameter list specifies any parameters needed

    by the constructor in superclassSuper() must always be the first statement inside

    subclass constructor

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    36/50

    36

    Using Super

    Class BoxWeight extends Box{double weight;BoxWeight(double w, double h, double d,double m);super(w,h,d);weight = m;

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    37/50

    37

    Second use of super

    super.member

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    38/50

    38

    Using Super Class A{

    int i;}Class B extends A{

    int i;B(int a, int b){ super.i = a; i=b;}

    void show(){System.out.println(I in superclass + super.i);System.out.println( I in subclass: + i);}

    Class useSuper{public static void main(String args[])B obj1 = new B(1, 2);

    obj1.show();}

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    39/50

    39

    When Constructors are Called

    Class A{A(){ System.out.println( inside As const);}

    Class B extends A{B(){ System.out.println( inside Bs const);}

    }

    Class C extends B{C(){ System.out.println( inside Cs const);}

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    40/50

    40

    Class callConst{ C obj = new C();}

    OutputInside As Constructor

    Inside Bs Constructor Inside Cs Constructor

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    41/50

    41

    Method Overriding

    When method in a subclass has same nameand type signature as method in its superclassthen method in subclass is said to override

    method in superclass

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    42/50

    42

    Dynamic Method Despatch

    Class A{callme(){ System.out.println( inside As callme);}

    Class B extends A{callme(){ System.out.println( inside Bs call me);}

    }Class C extends B{

    callme(){ System.out.println( inside Cs callme);}

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    43/50

    43

    Class Dispatch{ public static void main(String args[])

    A a = new A();

    B b = new B();C c = new C();A r ; r = a;r.callme(); r = b;

    r.callme(); r =c;r.callme();

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    44/50

    44

    Abstract Classes

    Super class that declares the structure of agiven abstraction without providing completeimplementation

    Super class that defines a generalized formand leave specific implementation tosubclassesAll methods which needs to be declared aredeclared as abstractAny class which contains abstract methods isdefined as abstract class

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    45/50

    45

    Abstract Classes

    abstract class A{ abstract void callme();

    void callmetoo()

    { System.out.println(This is a concrete method);}class B extends A{B b = new B();

    void callme(){ System.out.println(Bs implementation of callme);}

    }

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    46/50

    46

    Using final

    Keyword final has three usesCreate equivalent of a named constantWhen used with method name, it prevents themethod from being overridenWhen used with a class name it prevents theclass from being inherited.

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    47/50

    47

    Passing Objects as Parameters

    Both Common and right to pass objects toclassesAlready defined classes as well as custom

    classes can be sent as parameters

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    48/50

    48

    Argument Passing

    Two Ways through which a computer Language can pass Arguments

    Call-by-value Method Copies the value of an

    argument into formal parameters of subroutine Call-by-reference Reference to an argument (not

    values of the arguments) is passed to theparameter. Reference used to access actualarguments

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    49/50

    49

    The Object Class

    Object Clone()boolean equals(Object obj)Void finalize()Class getClass()String toString()Void notify

    Void notifyAllVoid wait()

  • 8/6/2019 Oop Concepts & Abstract Class ,Inheritance

    50/50

    Lab3