Java Programming - PowerPoint PPT Presentation

1 / 27
About This Presentation
Title:

Java Programming

Description:

Contents. Extending a Class. Constructors. Overloading and Overriding methods. Class Compatibility ... class ZZ { // ZZ IsA Object. String str; // ZZ HasA ... – PowerPoint PPT presentation

Number of Views:27
Avg rating:3.0/5.0
Slides: 28
Provided by: ebizUa
Category:

less

Transcript and Presenter's Notes

Title: Java Programming


1
Java Programming
  • CHAPTER 3 5
  • Extending Classes and Nested Classes

2
Contents
  • Extending a Class
  • Constructors
  • Overloading and Overriding methods
  • Class Compatibility
  • The Object Class
  • Cloning of Objects
  • Shallow and Deep Copy
  • Nested Types

3
Introduction
  • Polymorphism means that an object of a given
    class can behave as its own class or any class it
    extends
  • A subclass extends its superclass
  • The class contract is
  • the collection of methods and fields that are
    accessible from outside a class, together with
  • the description of how those members are expected
    to behave
  • Class extension provides 2 forms of inheritance
  • inheritance of contract or type
  • inheritance of implementation
  • Specialization is when the subclass defines new
    behavior and so becomes a specialized version of
    its superclass

4
An Extended Class
  • Every class in Java is extended from another
    class
  • When the class directly extends Object then it is
    not necessary to specify that
  • Only public class Attr is enough
  • The Object class is the root of the class
    hierarchy
  • Object defines methods that can be used by any
    class, e.g. toString
  • import java.util.StringBuffer
  • public class Attr extends Object
  • private final String name
  • private Object value // set to null by default
  • public Attr(String name)
  • this.name name
  • public Attr(final String n,final Object v)
  • name n
  • value v
  • public String getName()
  • return name
  • public Object getValue()
  • return value
  • public String toString() // more efficient

Object
Attr
5
Constructors in Extended Classes
  • The Extend class contains the fields and inherits
    the methods from the Base class
  • Constructors are not like other methods and they
    are not inherited
  • Constructors belong to the class that has defined
    them
  • Each class must define the constructors it needs
    to initialize its state
  • Constructors can be invoked from other
    constructors by a this or super call
  • class Base
  • String str
  • Base()
  • str not set yet
  • Base(String s)
  • str s
  • public String toString()
  • return str
  • class Extend extends Base
  • Double dbl
  • Extend(Double d)
  • dbl d
  • str set in Extend
  • Extend(String s,Double d)

6
Constructor Order Dependencies
  • When an object is created, then
  • Memory is allocated for all its fields
  • Each field is set to a default initial value
  • Invoke a superclass constructor
  • Initialize the fields using their initializers
    and any initialization blocks
  • Execute the body of the constructor
  • class XX
  • int xa 10
  • int xb
  • XX() xb 5
  • class YY
  • int ya 20
  • YY() xb ya
  • YY y new YY()
  • allocate memory for 3 int fields
  • set fields to 0
  • YY constructor invoked
  • XX constructor invoked
  • Object constructor invoked
  • xa set to 10
  • in XX constructor xb set to 5
  • ya set to 20
  • in YY constructor xb set to 25

7
Overloading and Overriding Methods
  • Overloading a method is defining more than one
    method with the same name
  • Overriding a method is replacing the superclass
    method with an own
  • class XX
  • void method()
  • void method(String s)
  • class YY
  • void method(String s)

8
Accessing Inherited Members
  • When invoking a method via an object reference,
    the actual class of the object governs what
    implementation is used
  • When accessing a field via an object reference,
    the declared type of the reference is used
  • import static java.lang.System.
  • class XX
  • String str X
  • void show()
  • out.println(XX.show str)
  • class YY extends XX
  • String str Y
  • void show()
  • out.println(YY.show str)
  • public static void main(String args)
  • final YY ext new YY()

9
Accessibility and Overriding
  • A method can be overridden only if accessible
  • If the method is not accessible then it is not
    inherited, and it cannot be overridden
  • If a subclass defines a method that has the same
    signature and return type as the superclass
    private method they are completely unrelated
  • In that case the subclass method does not
    override the superclass private method
  • import static java.lang.System.
  • class XX
  • private void show()
  • out.println(XX.show)
  • class YY extends XX
  • public void show()
  • out.println(YY.show)
  • public static void main(String args)
  • final YY ext new YY()
  • final XX sup ext

10
The super Keyword
  • Like this, super is available in all nonstatic
    methods of a class
  • super is used to refer to the superclass part of
    the current object
  • super.method always picks the method from the
    superclass
  • super.field always picks the field from the
    superclass part
  • import static java.lang.System.
  • class XX
  • int x 5
  • public void show()
  • out.println(XX.show x)
  • class YY extends XX
  • int x 6
  • public void show()
  • super.show()
  • out.println(YY.show super.x)
  • public static void main(String args)
  • final YY ext new YY()
  • final XX sup ext

11
Compatibility
  • assignment compatibility YY is a subtype of XX
  • but XX is not a subtype of YY
  • XX is higher in the hierarchy and thus a wider or
    less specific type
  • YY is a narrower or more specific type
  • null can be assigned to a variable of any type
  • explicit type casting
  • XX sup (YY) ext
  • YY ext (XX) sup // must do!
  • class XX
  • public void show()
  • class YY extends XX
  • public void show()
  • public static void main(String args)
  • YY ext new YY()
  • XX sup ext // widening
  • ext ? sup
  • ext (YY)sup // narrowing

Object
higher
XX
lower
YY
12
Testing for Type
  • the instanceof operator is used to test for type
  • if the a instanceof B expression evaluates to
    true then a is assignment compatible with type B
  • if (null instanceof aType) always evaluates to
    false
  • class XX
  • public void show()
  • class YY extends XX
  • public void show()
  • public static void main(String args)
  • YY ext
  • XX sup1 new YY()
  • XX sup2 new XX()
  • if (sup1 instanceof YY)
  • ext (YY) sup1
  • else if (sup2 instanceof XX)

13
What protected Really Means?
  • protected means that any class that extends this
    class or belongs to the same package as this
    class can also access its fields and methods
  • Therefore, if Extend would take an object of
    class Base and use it as a Base then Extend
    cannot access its protected members even though
    it inherits from Base because Base belongs to a
    different package

java.lang
packageX
packageY
Object
Base
protected
Extend
access
no access
access
14
final Methods and Classes
  • A final class cannot be extended
  • A final method cannot be overridden
  • final methods simplify optimizations when
    compiling the code this is known as inlining
  • inlining makes code run faster
  • final class XX
  • class YY extends XX
  • class XX
  • final void method ()
  • class YY extends XX
  • void method ()

15
Inlining
  • class XX
  • int i 4
  • int get () return i
  • int value new XX().get()
  • class YY
  • int i 8
  • final int get return i
  • int value new YY().get()
  • After compilation it looks as if the source is
  • int value new XX().get()
  • int value new YY().i // this method invocation
    is replaced with its body

16
Abstract Classes and Methods
  • An abstract class defines only part of its
    implementation
  • Abstract classes cannot be instantiated
  • concrete class is the opposite of abstract
  • A concrete class implements all the methods
  • A concrete method from the superclass can be
    overridden into an abstract
  • abstract class XX
  • abstract void method()
  • XX xx new XX() // error
  • class YY extends XX
  • void method()
  • YY yy new YY()

17
The Object Class
  • The Object class is the root of the class
    hierarchy
  • Every class directly or indirectly inherits from
    Object
  • Therefore we can cast (a widening) any type into
    an Object
  • Methods defined by Object
  • public boolean equals(Object)
  • protected Object clone()
  • public final Classlt?gt getClass()
  • public String toString()

18
Cloning Objects
  • The Object.clone method makes an exact copy of
    the object that has invoked the method
  • This is a shallow copy
  • The object to be cloned must implement the
    Cloneable interface
  • import static java.lang.System.
  • class XX implements Cloneable
  • public int i
  • public static void main(String args)
  • final XX orig new XX()
  • orig.i 5
  • XX clone orig.clone()
  • out.println(clone.i clone.i)
  • orig.i 6
  • out.println(clone.i clone.i)
  • ? clone.i 5

19
Shallow and Deep Copy
  • import static java.lang.System.
  • class XX implements Cloneable
  • public int i new int1
  • public static void main(String args)
  • final XX orig new XX()
  • orig.i0 5
  • final XX clone orig.clone()
  • out.println(clone.i clone.i0)
  • orig.i0 6
  • out.println(clone.i clone.i0)
  • import static java.lang.System.
  • class XX implements Cloneable
  • public int i new int1
  • protected Object clone()
  • try
  • XX clone (XX)super.clone()
  • clone.i new int1
  • clone.i0 i0
  • catch (CloneNotSupportedException )
  • public static void main(String args)
  • final XX orig new XX()
  • orig.i0 5

20
Extending Classes How and When
  • The ability to extend a class is at the core of
    object-oriented approach
  • By extending we can add new fields and methods
    while reusing the rest from the super class
  • IsA relationship the extension creates a new
    kind of object that is a kind of the original
    class
  • HasA relationship one object uses another
    object to store state or do work, i.e. it has a
    reference to that object
  • class XX // XX IsA Object
  • int i
  • void method()
  • class YY extends XX
  • // YY IsA XX
  • class ZZ // ZZ IsA Object
  • String str // ZZ HasA String
  • void method()
  • str store data

21
Nested Classes
  • A class can be defined inside another class
  • Benefits
  • to structure and scope members
  • to connect logically related objects
  • A nested class is considered a part of its
    enclosing class
  • They share a trust relationship, i.e. everything
    is mutually accessible
  • Nested types could be
  • static allows simple structuring of types
  • nonstatic defines a special relationship
    between a nested object and an object of the
    enclosing class

22
Static Nested Types
  • Acts like any top-level class
  • It can extend any class including the class it is
    a member of
  • It can be declared abstract or final
  • A static nested class can be extended by any
    class to which it is accessible, but
  • The extended class does not inherit the
    privileged access that the nested class has to
    the enclosing class
  • public class BankAccount
  • private long number
  • private static long bankID
  • public Permissions permissionsFor(Person who)
  • Permissions p new Permissions()
  • p.method(this)
  • return p
  • public static class Permissions
  • public boolean canDeposit
  • public boolean canWithdraw
  • void method(BankAccount acc)
  • long bid bankID
  • long num acc.number

23
Inner Classes
  • Inner classes are associated with instances of a
    class
  • Inner classes cannot have static members
    including static nested types
  • Inner classes can have final static fields that
    are constant
  • Inner classes can extend any other class,
    implement any interface, or be extended
  • When an inner class object is created inside a
    method of the enclosing class the current object
    this is automatically associated with it
  • qualifiedthis
  • public class BankAccount
  • private long number
  • private static long bankID
  • public Permissions permissionsFor(Person who)
  • Permissions p new Permissions()
  • // equal to this.new Permissions()
  • p.method()
  • return p
  • public class Permissions
  • public boolean canDeposit
  • public boolean canWithdraw
  • void method()
  • long bid bankID
  • long num number

in scope
24
Extended Inner Classes
  • An inner class can be extended
  • Objects of the extended class must remain
    associated with objects of the original enclosing
    class or a subclass
  • class Outer
  • class Inner
  • class ExtendOuter extends Outer
  • class ExtendInner extends Inner
  • Inner ref new ExtendInner()
  • class Unrelated extends Outer.Inner
  • Unrelated(Outer ref)
  • ref.super()

25
Local Inner Classes
  • Can be defined in code blocks and they are local
    and accessible to that block
  • They do not have access modifiers (e.g. private,
    public) and cannot be static
  • They are not members of the class to which the
    block belongs
  • A local inner class can access all the variables
    in that block, and static variables, but a local
    variable or method parameter must be declared
    final
  • import static java.lang.System.
  • public class EnclosingClass
  • int x 55
  • public void enclosingMethod(final int a)
  • int z 44
  • final int q 32
  • class LocalInner
  • private int x 17
  • public void innerMethod()
  • out.println(x) // ? 17
  • out.println(q) // ? 32
  • out.println(a) // ? 99
  • out.println(this.x) // ? 17
  • out.println(EnclosingClass.this.x) // ?
    55

26
Anonymous Inner Classes
  • Extend a class or implement an interface
  • They are defined at the same time when
    instantiated with new, as part of a statement
  • They cannot have explicit constructors because
    they have no name
  • import static java.lang.System.
  • public class EnclosingClass
  • int x 55
  • public void anotherMethod2()
  • out.println(new Object()
  • private int x 17
  • public String toString()
  • return "Inner x " x
  • " Enclosing x " EnclosingClass.this.x
  • )
  • ? Inner x 17 Enclosing x 55

27
Inner Class Categories
Inner Classes
Local Inner Classes
Member Inner Classes
Anonymous Local Inner Classes
Nonstatic Member Inner Classes
Named Local Inner Classes
Static Member Inner Classes
Write a Comment
User Comments (0)
About PowerShow.com