Inheritance and Class Hierarchies - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

Inheritance and Class Hierarchies

Description:

A JetPlane has multiple jet engines. Chapter 3: Inheritance and Class ... public LapTop(String man, String proc, int ram, int disk, double screen, double wei) ... – PowerPoint PPT presentation

Number of Views:41
Avg rating:3.0/5.0
Slides: 32
Provided by: phil197
Category:

less

Transcript and Presenter's Notes

Title: Inheritance and Class Hierarchies


1
Inheritance and Class Hierarchies
  • Chapter 3

2
Chapter Objectives
  • To understand inheritance and how it facilitates
    code reuse
  • To understand how Java determines which method to
    execute when there are multiple methods with the
    same name in a class hierarchy
  • To learn how to define and use abstract classes
    as base classes in a hierarchy
  • To study class Object and its methods and to
    learn how to override them
  • To learn how to clone an object and to
    understand the difference between a true clone
    (deep copy) and a shallow copy

3
Chapter Objectives (continued)
  • To understand why Java does not implement
    multiple inheritance and to see how you can gain
    some of the advantages of multiple inheritance
    through interfaces and delegation
  • To become familiar with a class hierarchy for
    drawable shapes
  • To understand how to create packages and to learn
    more about visibility

4
3.1 Introduction to Inheritance and Class
Hierarchies
  • Object Oriented Programming
  • OOP enables programmers to reuse previously
    written code saved as classes (rich set of
    libraries)
  • Inheritance mechanism allows you to capture the
    idea that one thing may be a refinement or
    extension of another. You can create a new class
    by extending the existing class
  • Inheritance
  • All Java classes are arranged in a hierarchy,
    starting with Object, which is the superclass of
    all Java classes
  • The subclass/superclass relationship (is-a
    relationship) is transitive.

5
RuntimeException is an Exception, but the
converse is not true.
6
Is-a Versus Has-a Relationships
  • One misuse of inheritance is confusing the has-a
    relationship with the is-a relationship
  • The has-a relationship means that one class has
    the second class as a part.
  • public class JetPlane extends Airplane
  • private JetEngine jets
  • A JetPlane is an AirPlane. (It has all the
    features of AirPlanes with additional features
    that make it a JetPlane.)
  • A JetPlane has multiple jet engines.

7
Java Constructors
  • If no constructors are defined for a class, the
    no-parameter constructor for that class will be
    given by Java, which initialize the classs
    fields with their default values according to
    their types.
  • Default values
  • Reference variables null
  • Simple variables numbers 0, boolean false
  • If there is any constructor defined in a class,
    Java doesnt do anything about constructors. It
    means the constructors defined in the class are
    all the class will have.

8
Example

Consider the following code in a test
program Employee e new Employee() Is new
Employee() legal ? If the Employee class a) has
neither 1 nor 2 yes b) has only 1 yes
(the value of name is initialized to not
null) c) has only 2 no d) has both 1 and 2
yes
  • public class Employee
  • private String name
  • private double salary
  • public Employee()
  • name
  • public Employee(String s)
  • name s
  • public double getSalary()
  • return salary
  • public void raiseSalary(double i)
  • salary i

1
2
9
A Superclass and a Subclass
  • Consider two classes Computer and Laptop
  • A laptop is a kind of computer and is therefore a
    subclass of computer

10
public class Computer private String
manufacturer private String processor
private int ramSize private int diskSize
public Computer(String man, String processor,
int ram, int disk) manufacturer man
processor processor // not
recommended. Use a different name !
ramSize ram diskSize disk
// Other Methods are defined here. Please refer
to the textbook pp.129 public String
toString() String result
"Manufacturer " manufacturer
"\nCPU " processor "\nRAM "
ramSize " megabytes" "\nDisk "
diskSize " gigabytes" return result

11
Initializing Data Fields in a Subclass(subclass
constructors)
  • Private data fields inherited from a super class
    must be initialized by invoking the super classs
    constructor with the appropriate parameters.
  • public LapTop(String man, String proc, int
    ram,
  • int disk,double screen, double
    wei)
  • super(man, proc, ram, disk)
  • screenSize screen
  • weight wei
  • The super call must be the first line in the
    subclass constructor.
  • If the sublcass constructor does not invoke a
    superclass constructor, Java invokes the default
    (no-parameter) constructor for the superclass.

12
Initializing Data Fields in a Subclass(subclass
constructors)
  • If there is no appropriate constructor available
    in the immediate super class, you will get a
    syntax error Constructor not defined.
  • For example, the following constructor of LapTop
    class will generate a syntax error Java calls
    the implicit super() which doesnt exist in the
    super class Computer.
  • public LapTop(String man, String proc, int ram,
    int disk, double screen, double wei)
  • screenSize screen
  • weight wei

13
Protected Visibility for Superclass Data Fields
  • private only the class that defines it
  • public any class
  • default (package) classes in the same package.
    The default is not a java keyword. If a class
    does not specify any visibility, the data field
    has a package visibility.
  • protected any subclass classes in the same
    package.
  • In general, it is better to use private
    visibility for instance variables because
    subclasses may be written by different
    programmers and it is always good practice to
    restrict and control access to the superclass
    data fields

14
3.2 Method Overriding
  • A subclass can override an inherited method from
    the superclass. Once a method is overriden, the
    overriden method will replace the inherited one
    in the subclass.
  • A overriden method must have the same method
    signature as the corresponding super class
    method.
  • Late binding and polymorphism

overriden method
15
The overriden toString method in Laptop
  • public String toString()
  • String result super.toString()
  • "\nScreen size " screenSize "
    inches"
  • "\nWeight " weight " pounds"
  • return result
  • A super.method()calls the method() of the super
    class.

16
Polymorphism and Late binding
  • A variable of a superclass type can refer to an
    object of a subclass type
  • The compiler checks the availability of a method
    according to the type of variable.
  • Polymorphism In OOP, a method with the same
    signature can appear in many different forms.
    Polymorphism is the ability to select the
    appropriate method for a particular object.
  • Late binding JVM determines which method to
    invoke is at run time (based on the actual object
    the method is activated on.)

17
public class BankAccount private double
balance public void transfer(BankAccount b,
double amount) this.withdraw(amount)
b.deposit(amount) // assume withdraw and
deposit are declared here.
public class SavingsAccount extends BankAccount
public class TDA extends SavingsAccount.
public class Test public static void main
(String args) // Assume ba and sa are
created here. ba.transfer(sa, 1000)
18
Constructor/Method Overloading
  • Constructor/Method overloading
  • having multiple constructor/methods with the
    same name but different signatures in a class
  • public LapTop(String man, String proc, int ram,
    int disk, double screen, double wei)
  • super(man, proc, ram, disk)
  • screenSize screen
  • weight wei
  • public LapTop(String proc, int ram, int disk,
    double screen, double wei)
  • this(DEFAULT_LT_MAN, proc, ram, disk, screen,
    wei)
  • this() invokes the constructor for the current
    class whose parameter list matches with the
    argument list.

19
The Method toString
  • You should always override the toString method if
    you want to represent an objects state.
  • If you do not override it, the inherited
    toString method from java.lang.Object will return
    a string such as ArrayBasedPD_at_ef08879, which is
    the hashcode of an object.
  • When would Java call toString method for you ?
  • System.out.println( r.toString() )
  • String s r.toString()

20
The method equals
  • To learn how to write an equals method, you need
    to know about type casting in Java.
  • Java is a strongly typed language
  • Every variable has a type.
  • All assignments are checked by the compiler for
    their type compatibility.
  • Type casting between two classes can be
    considered only if they have an is-a
    (inheritance) relationship.
  • Type casting upcast and downcast

21
Upcasts
  • casting from a more specific type to a more
    general type
  • e.g.) Object aThing new Integer(25)
  • treat the specific as the more general
  • always safe, and thus an explicit casting
    operator is not necessary and rarely used.

Object
Person
BankAccount
Employee
SavingsAccount
Integer
22
Operations Determined by Type of Reference
Variable
  • Object aThing new Integer(25)
  • When you access the Integer object through
    aThing,
  • you should treat it as an Object. Therefore,
    any operation
  • specific to Integer cannot be activated on
    aThing.
  • e.g.) aThing.intValue() // compilation error
  • The type of reference variable is Object, and
    thus, the
  • compiler checks if intValue() is available
    for an Object.

23
Operations Determined by Type of Reference
Variable
  • public void someMethod(Object aThing)
  • if (aThing.equals(someObjectHere))
  • // do something
  • The compiler checks an equals method is available
    for Object, the type of aThing.
  • The JVM determines which specific equals method
    will be called at run time based on the actual
    object aThing references (polymorphism).
  • With this method call, someMethod(new
    Integer(30))
  • aThing now references an Integer object, and
    thus the JVM calls the equals method of Integer.
  • Note that upcasting is implicitly done through
    parameter passing aThing new Integer(30)

24
Downcasts
  • Treats the general as the more specific.
  • Not always safe
  • Hence compiler requires explicit cast.
  • (ClassName)objectExpression
  • In the following code, the cast operator
    (Integer) tells the compiler that aThing actually
    references an Integer object.
  • Object aThing new Integer(25)//upcast
  • Integer num (Integer)aThing //downcast

25
Downcasting at Runtime
  • Explicit cast only satisfies compiler.
  • Downcast may still fail at run time.
  • Failed downcast throws ClassCastException
  • Use instanceof
  • op1 instanceof op2
  • Returns true if op1 is an instance of op2

26
The equals method of Employee
  • / Determines whether the current object matches
    its argument.
  • _at_param the object to be compared to the
    current object
  • _at_return true if the objects have the same
    name and addresses otherwise, return false.
  • /
  • public boolean equals(Object obj)
  • if (obj instanceof Employee)
  • Employee other (Employee) obj
  • return name.equals(other.name)

  • address.equals(other.address)
  • else return false

27
Java 5.0 Reduces Need for Casting
  • Autoboxing/unboxing eases the conversion between
    a primitive type and its corresponding wrapper
    type

nextCh
ch
Character
x
x
  • Note that ch is a reference variable and nextCh
    is
  • a simple variable.

28
Packages
  • The Java API is organized into packages
  • The package to which a class belongs is declared
    by the first statement in the file in which the
    class is defined using the keyword package
    followed by the package name
  • All classes in the same package are stored in the
    same directory or folder
  • All the classes in one folder must declare
    themselves to be in the same package

29
Package
  • I. Declaring a Package package pkgname
  • ex) package edu.sjsu.simulations
  • More than one file can include the same package
    statement.
  • A package should be located in a subdirectory
    that matches the package name
  • ex) the above package need to be stored in
  • edu\sjsu\simulations
  • II. Using Packages import statement
  • After its own package declaration but before
    anything else.
  • Import individual class names or all class names
    in package
  • ex) import java.util.Stack or
  • import java.util.

30
CLASSPATH
  • Where do SDK tools (javac, java, etc) look for
    packages ? in CLASSPATH
  • Each location is root of a package structure
  • ex) c\somewhere\classesc\otherplace.
  • Setting a classpath
  • Set CLASSPATHpath1path2
  • Sdktool -classpath path1path2 (preferred)
  • Default classpath is the current directory

31
CLASSPATH (cont.)
  • JCL (Java Class Library) useful packages comes
    with the Java Language
  • rt.jar contains the standard library for the SDK.
    You never need to include it in the classpath
    when you use SDK utilities they know where
    rt.jar is.
  • ex) java.util is in rt.jar
Write a Comment
User Comments (0)
About PowerShow.com