SlideShare a Scribd company logo
CSC 222: Computer Programming II

                                   Spring 2005


      Inheritance
              derived class, parent class
              inheriting fields & methods, overriding fields and methods
              bank account example
              IS-A relationship, polymorphism
              super methods, super constructor




                                                                                    1




Inheritance
  inheritance is a mechanism for enhancing existing classes
        one of the most powerful techniques of object-oriented programming
        allows for large-scale code reuse

  with inheritance, you can derive a new class from an existing one
        automatically inherit all of the fields and methods of the existing class
        only need to add fields and/or methods for new functionality



   example:
    • savings account is a bank account
      with interest
    • checking account is a bank account
      with transaction fees

                                                                                    2
BankAccount class                              public class BankAccount
                                               {
                                                 private double balance;
                                                 private int accountNumber;
                                                 private static int nextNumber = 1;
  here is an implementation of a
                                                public BankAccount()
  basic BankAccount class                        {
                                                     balance = 0;
                                                     accountNumber = nextNumber;
                                                     nextNumber++;
        stores account number and                }
        current balance                            public int getAccountNumber()
                                                   {
                                                       return accountNumber;
        uses static field to assign each           }
        account a unique number
                                                   public double getBalance()
                                                   {
        accessor methods provide access            }
                                                       return balance;

        to account number and balance
                                                   public void deposit(double amount)
                                                   {
        deposit and withdraw methods                   balance += amount;
        allow user to update the balance           }

                                                   public void withdraw(double amount)
                                                   {
                                                       if (amount >= balance) {
                                                           balance -= amount;
                                                       }
                                                   }
                                               }                                            3




Specialty bank accounts
  now we want to implement SavingsAccount and CheckingAccount
        a savings account is a bank account with an associated interest rate, interest is
        calculated and added to the balance periodically
        could copy-and-paste the code for BankAccount, then add a field for interest rate
        and a method for adding interest

        a checking account is a bank account with some number of free transactions, with a
        fee charged for subsequent transactions
        could copy-and-paste the code for BankAccount, then add a field to keep track of
        the number of transactions and a method for deducting fees


  disadvantages of the copy-and-paste approach
        tedious work
        lots of duplicate code – code drift is a distinct possibility
          if you change the code in one place, you have to change it everywhere or else
              lose consistency (e.g., add customer name to the bank account info)
        limits polymorphism (will explain later)

                                                                                            4
SavingsAccount class
  inheritance provides a better solution
       can define a SavingsAccount to be a special kind of BankAccount
           automatically inherit common features (balance, account #, deposit, withdraw)
       simply add the new features specific to a savings account
           need to store interest rate, provide method for adding interest to the balance
       general form for inheritance:
            public class DERIVED_CLASS extends EXISTING_CLASS
            {
              ADDITIONAL_FIELDS

                ADDITIONAL_METHODS
            }
                                     public class SavingsAccount extends BankAccount
                                     {
                                       private double interestRate;
  note: the derived class
                                         public SavingsAccount(double rate)
  does not explicitly list               {
  fields/methods from the                }
                                           interestRate = rate;

  existing class (a.k.a. parent
                                         public void addInterest()
  class) – they are inherited            {
  and automatically                        double interest = getBalance()*interestRate/100;
                                           deposit(interest);
  accessible                             }
                                     }                                                               5




Using inheritance

  BankAccount generic = new BankAccount();               // creates bank account with 0.0 balance
  ...
  generic.deposit(120.0);                                // adds 120.0 to balance
  ...
  generic.withdraw(20.0);                                // deducts 20.0 from balance
  ...
  System.out.println(generic.getBalance());              // displays current balance: 100.0




  SavingsAccount passbook = new SavingsAccount(3.5);//      creates savings account, 3.5% interest
  ...
  passbook.deposit(120.0);                          //      calls inherited deposit method
  ...
  passbook.withdraw(20.0);                          //      calls inherited withdraw method
  ...
  System.out.println(passbook.getBalance());        //      calls inherited getBalance method
  ...
  passbook.addInterest();                           //      calls new addInterest method
  ...
  System.out.println(passbook.getBalance());        //      displays 103.5




                                                                                                     6
CheckingAccount class
                                        public class CheckingAccount extends BankAccount
                                        {
  can also define a class that            private int transactionCount;
                                          private static final int NUM_FREE = 3;
  models a checking account               private static final double TRANS_FEE = 2.0;

      again, inherits basic features        public CheckingAccount()
                                            {
      of a bank account                       transactionCount = 0;
      assume some number of free            }

      transactions                          public void deposit(double amount)
      after that, each transaction          {
                                              super.deposit(amount);
      entails a fee                           transactionCount++;
                                            }

      must override the deposit and         public void withdraw(double amount)
      withdraw methods to also              {
                                              super.withdraw(amount);
      keep track of transactions              transactionCount++;
                                            }

      can call the versions from the        public void deductFees()
      parent class using super              {
                                              if (transactionCount > NUM_FREE) {
                                                double fees =
        super.PARENT_METHOD();                      TRANS_FEE * (transactionCount – NUM_FREE);
                                                super.withdraw(fees);
                                              }
                                              transactionCount = 0;
                                            }
                                        }                                                        7




Interfaces & inheritance
  recall that with interfaces
         can have multiple classes that implement the same interface
         can use a variable of the interface type to refer to any object that implements it
          Comparable c1 = new String("foo");
          Comparable c2 = new Integer(5);

         can use the interface type for a parameter, pass any object that implements it
          public void DoSomething(Comparable c)
          {
            . . .
          }

          ---------------------------------------------

          DoSomething("foo");

          DoSomething(5);                   // note: 5 is autoboxed into an Integer



  the same capability holds with inheritance
         could assign a SavingsAccount object to a variable of type BankAccount
         could pass a CheckingAccount object to a method with a BankAccount parameter
                                                                                                 8
IS-A relationship
  the IS-A relationship holds when inheriting
        an object of the derived class is still an object of the parent class
        anywhere an object of the parent class is expected, can provide a derived
        object

        consider a real-world example of inheritance: animal classification


                                          ANIMAL




                       FISH               MAMMAL                  BIRD




                CARP     GOLDFISH   DOG    CAT     HUMAN   DUCK     BLUEJAY




                                                                                             9




Polymorphism
  in our example
        a SavingsAccount is-a BankAccount (with some extra functionality)
        a CheckingAccount is-a BankAccount (with some extra functionality)

        whatever you can do to a BankAccount (e.g., deposit, withdraw), you can do with
        a SavingsAccount or Checking account
          • derived classes can certainly do more (e.g., addInterest for SavingsAccount)
          • derived classes may do things differently (e.g., deposit for CheckingAccount)

  polymorphism: the same method call can refer to different methods when
     called on different objects
        the compiler is smart enough to call the appropriate method for the object
          BankAccount acc1 = new SavingsAccount(4.0);
          BankAccount acc2 = new CheckingAccount();
          acc1.deposit(100.0);            // calls the method defined in BankAccount
          acc2.deposit(100.0);            // calls the method defined in CheckingAccount


        allows for general-purpose code that works on a class hierarchy

                                                                                            10
import java.util.ArrayList;

 public class AccountAdd
 {
                                                                           Example use
   public static void main(String[] args)
   {
     SavingsAccount xmasFund = new SavingsAccount(2.67);
     xmasFund.deposit(250.0);

         SavingsAccount carMoney = new SavingsAccount(1.8);
         carMoney.deposit(100.0);                                          note: in addToAll, the
         CheckingAccount living = new CheckingAccount();
                                                                           appropriate deposit
         living.deposit(400.0);                                            method is called on
         living.withdraw(49.99);
                                                                           each BankAccount
         ArrayList<BankAccount> finances = new ArrayList<BankAccount>();
         finances.add(xmasFund);
                                                                           (depending on
         finances.add(carMoney);                                           whether it is really a
         finances.add(living);
                                                                           SavingsAccount or
         addToAll(finances, 5.0);
         showAll(finances);
                                                                           CheckingAccount)
     }

     private static void addToAll(ArrayList<BankAccount> accounts, double amount)
     {
       for (int i = 0; i < accounts.size(); i++) {
         accounts.get(i).deposit(amount);
       }
     }

     private static void showAll(ArrayList<BankAccount> accounts)
     {
       for (int i = 0; i < accounts.size(); i++) {
         System.out.println(accounts.get(i).getAccountNumber() + ": $" +
                            accounts.get(i).getBalance());
       }
     }
 }                                                                                              11




In-class exercise

     define the BankAccount, SavingsAccount, and CheckingAccount classes

     create objects of each class and verify their behaviors

     are account numbers consecutive regardless of account type?
               should they be?

     what happens if you attempt to withdraw more than the account holds?
               is it ever possible to have a negative balance?




                                                                                                12
Another example: colored dice
 public class Die
 {                                                    we already have a class that models
   private int numSides;
   private int numRolls;
                                                      a simple (non-colored) die
                                                             can extend that class by adding a color
     public Die(int sides)                                   field and an accessor method
     {
       numSides = sides;                                     need to call the constructor for the Die
       numRolls = 0;                                         class to initialize the numSides and
     }                                                       numRolls fields
     public int roll()
     {                                                           super(ARGS);
       numRolls++;
       return (int)(Math.random()*numSides) + 1;
     }                                                public class ColoredDie extends Die
                                                      {
     public int getNumSides()                           private String dieColor;
     {
       return numSides;                                   public ColoredDie(int sides, String color)
     }                                                    {
                                                            super(sides);
     public int getNumRolls()                               dieColor = color;
     {                                                    }
       return numRolls;
     }                                                    public String getColor()
 }                                                        {
                                                            return dieColor;
                                                          }
                                                      }                                            13




ColoredDie example                       import java.util.ArrayList;
                                         import java.util.Collections;

                                         public class RollGame
                                         {
     consider a game in which              private ArrayList<ColoredDie> dice;
                                           private static final int NUM_DICE = 5;
     you roll a collection of dice
                                             public RollGame()
     and sum their values                    {
                                               dice = new ArrayList<ColoredDie>();

                                                 dice.add(new ColoredDie(6, "red"));
          there is one "bonus" red die           for (int i = 1; i < NUM_DICE; i++) {
          that counts double                     }
                                                   dice.add(new ColoredDie(6, "white"));

                                                 Collections.shuffle(dice);
                                             }

                                             public int rollPoints()
                                             {
                                               int total = 0;
                                               for (int i = 0; i < NUM_DICE; i++) {
                                                 int roll = dice.get(i).roll();
                                                 if (dice.get(i).getColor().equals("red")) {
                                                   total += 2*roll;
                                                 }
                                                 else {
                                                   total += roll;
                                                 }
                                               }
                                               return total;
                                             }
                                         }                                                         14
GridWorld

  GridWorld is a
  graphical environment
  under development by
  Cay Horstmann

      based on the AP
      Marine Biology Case
      Study

      can place actors in a
      Grid and have them
      move around and
      interact




                                                                                          15




Downloading the GridWorld

  download www.creighton.edu/~davereed/csc222/Code/GridWorld.zip
         you can store the file anywhere, e.g., the Desktop

  extract all of the files

  start up BlueJ, select Open Project and browse to select GridWorld

  call the main method of the CritterDemo class
         the initial grid has a Rock and a Critter
         can click on the Step button to see one move of the Critter (Rocks don't move)
         can click on the Run button to see repeated moves

         can also click on a grid space to add a Rock or Critter


                                                                                          16
GridWorld base classes
  Grid<T>: an interface that defines a 2-dimensional grid of objects
     BoundedGrid<T>: a class that implements Grid<T>, using a 2-D array
     UnboundedGrid<T>: a class that implements Grid<T>, using a Map (later)

  Location: a class that encapsulates a location (row, col) on the Grid

  Actor: class that defines a generic actor that can move around a Grid
         public    int getDirection()
         public    Color getColor()
         public    void setColor(Color newColor)
         public    void turn(int angle)
         public    Location move(Location loc, Grid<Actor> gr)
         public    void act(Location loc, Grid<Actor> gr)


  act method is empty for Actor
         must define a class that inherits from Actor, overrides act to behave as desired

                                                                                            17




Rock class
  a rock is an actor that does nothing!
         must override the move method so that the rock can't move
         must override the setColor method since all rocks are black


           public class Rock extends Actor
           {
             // rocks don't move, so just returns current location
             public Location move(Location loc, Grid env)
             {
                 return loc;
             }

               // rocks are always black, so disable any color change
               public void setColor(Color newColor)
               {
                   // does nothing
               }
           }




                                                                                            18
Critter class
  a Critter is an animal that scurries around the grid
          if clear, it will move in its current direction
          if blocked, it will turn 135 degrees to the right (backwards diagonal)

      public class Critter extends Actor
      {
         public Critter()
         {
            setColor(Color.GREEN);
         }

          public Critter(Color color)
          {
             setColor(color);
          }

          public void act(Location loc, Grid<Actor> gr)
          {
             Location newLoc = move(loc, gr);
             if (loc.equals(newLoc)) {
                 turn(135); // if didn't move, then turn
            }
          }
      }


                                                                                          19




Other actors
  can define other Actor classes that define different behaviors
          Destroyer class
           moves similarly to Critter, but destroys any object it comes in contact with
           uses Grid method getAllNeighborLocations to get surrounding locations
           can then check each location to see if empty – if not, then remove contents


  can inherit from previously defined classes to modify behaviors
          FastCritter class
           moves similarly to Critter, but moves two steps instead of one
           since derived from Critter, could be used anywhere a Critter is expected

  other actors?


                                                                                          20

More Related Content

Viewers also liked

Nokia Asha 210 - Es
Nokia Asha 210 - EsNokia Asha 210 - Es
Nokia Asha 210 - Es
Martha L. Medina Pacheco
 
Presentación placa base y redes
Presentación placa base y redesPresentación placa base y redes
Presentación placa base y redes
hector102
 
Jingu kid Case Study
Jingu kid Case StudyJingu kid Case Study
Jingu kid Case Study
NeuronMediatech2
 
2012 Crestron Integration Award Winners
2012 Crestron Integration Award Winners2012 Crestron Integration Award Winners
2012 Crestron Integration Award Winners
Crestron Electronics
 
Magisterio Encuentro Educared
Magisterio Encuentro EducaredMagisterio Encuentro Educared
Magisterio Encuentro Educared
Educared - Fundación Telefónica
 
K jackson medical terminology chapter 11
K jackson medical terminology chapter 11K jackson medical terminology chapter 11
K jackson medical terminology chapter 11
Kimberly Jackson, MPH, MBA, MPA
 
Cartel coaching madrid lucia
Cartel coaching madrid luciaCartel coaching madrid lucia
Cartel coaching madrid lucia
Lucía Díaz Cubertoret
 
2w guia de_recomendacoes_de_seguranca
2w guia de_recomendacoes_de_seguranca2w guia de_recomendacoes_de_seguranca
2w guia de_recomendacoes_de_seguranca
_AXE_PM
 
Bill gatesdicea losadolescentes12
Bill gatesdicea losadolescentes12Bill gatesdicea losadolescentes12
Bill gatesdicea losadolescentes12
Juan Russo
 
11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...
11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...
11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...
Jeff Carter
 
Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...
Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...
Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...
Imma Aguilar Nàcher
 
Drush – Das Sackmesser für die Kommandozeile
Drush – Das Sackmesser für die KommandozeileDrush – Das Sackmesser für die Kommandozeile
Drush – Das Sackmesser für die Kommandozeile
Florian Latzel
 
A2 fr06 inventario de material bibliografico
A2 fr06 inventario de material bibliograficoA2 fr06 inventario de material bibliografico
A2 fr06 inventario de material bibliografico
iejcg
 
GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016
GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016
GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016
PAUL Carbony
 
MOCA iBeacons SDK for iOS 7
MOCA iBeacons SDK for iOS 7MOCA iBeacons SDK for iOS 7
MOCA iBeacons SDK for iOS 7
MOCA Platform
 
Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...
Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...
Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...
Istituto nazionale di statistica
 
Segunda unidad de estadistica
Segunda unidad de estadisticaSegunda unidad de estadistica
Segunda unidad de estadistica
Maria Lopez Hernandez
 
3D printing
3D printing3D printing
3D printing
Enrico Bassi
 
Teoria general del proceso i
Teoria general del proceso  iTeoria general del proceso  i
Teoria general del proceso i
karenm95
 

Viewers also liked (20)

Nokia Asha 210 - Es
Nokia Asha 210 - EsNokia Asha 210 - Es
Nokia Asha 210 - Es
 
Presentación placa base y redes
Presentación placa base y redesPresentación placa base y redes
Presentación placa base y redes
 
Jingu kid Case Study
Jingu kid Case StudyJingu kid Case Study
Jingu kid Case Study
 
2012 Crestron Integration Award Winners
2012 Crestron Integration Award Winners2012 Crestron Integration Award Winners
2012 Crestron Integration Award Winners
 
Magisterio Encuentro Educared
Magisterio Encuentro EducaredMagisterio Encuentro Educared
Magisterio Encuentro Educared
 
K jackson medical terminology chapter 11
K jackson medical terminology chapter 11K jackson medical terminology chapter 11
K jackson medical terminology chapter 11
 
Cartel coaching madrid lucia
Cartel coaching madrid luciaCartel coaching madrid lucia
Cartel coaching madrid lucia
 
2w guia de_recomendacoes_de_seguranca
2w guia de_recomendacoes_de_seguranca2w guia de_recomendacoes_de_seguranca
2w guia de_recomendacoes_de_seguranca
 
Bill gatesdicea losadolescentes12
Bill gatesdicea losadolescentes12Bill gatesdicea losadolescentes12
Bill gatesdicea losadolescentes12
 
Infoblatt entwicklung-und-projektionen
Infoblatt entwicklung-und-projektionenInfoblatt entwicklung-und-projektionen
Infoblatt entwicklung-und-projektionen
 
11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...
11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...
11813118 dogma-y-ritual-de-la-alta-magia-completo-eliphas-levi-130704185804-p...
 
Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...
Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...
Tecnopolítica e innovación: Nuevos escenarios, actores y relaciones. Presenta...
 
Drush – Das Sackmesser für die Kommandozeile
Drush – Das Sackmesser für die KommandozeileDrush – Das Sackmesser für die Kommandozeile
Drush – Das Sackmesser für die Kommandozeile
 
A2 fr06 inventario de material bibliografico
A2 fr06 inventario de material bibliograficoA2 fr06 inventario de material bibliografico
A2 fr06 inventario de material bibliografico
 
GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016
GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016
GLOBAL ASSET INTEGRITY, MAINTENANCE & INSPECTION MANAGEMENT SUMMIT 2016
 
MOCA iBeacons SDK for iOS 7
MOCA iBeacons SDK for iOS 7MOCA iBeacons SDK for iOS 7
MOCA iBeacons SDK for iOS 7
 
Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...
Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...
Leonello Tronti (SSPA), Presentazione del volume "Capitale umano: definizione...
 
Segunda unidad de estadistica
Segunda unidad de estadisticaSegunda unidad de estadistica
Segunda unidad de estadistica
 
3D printing
3D printing3D printing
3D printing
 
Teoria general del proceso i
Teoria general del proceso  iTeoria general del proceso  i
Teoria general del proceso i
 

Similar to Inheritance

The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
akshay1213
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdfAccount.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
anujmkt
 
Class
ClassClass
OOP: Classes and Objects
OOP: Classes and ObjectsOOP: Classes and Objects
OOP: Classes and Objects
Atit Patumvan
 
Banks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdfBanks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdf
rajeshjain2109
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
lienhard
 
In Visual Studios C# console app using multiple class files create a.pdf
In Visual Studios C# console app using multiple class files create a.pdfIn Visual Studios C# console app using multiple class files create a.pdf
In Visual Studios C# console app using multiple class files create a.pdf
sanjeevbansal1970
 
I need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfI need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdf
rajeshjangid1865
 
Hi,I have updated the code as per your requirement. Highlighted th.pdf
Hi,I have updated the code as per your requirement. Highlighted th.pdfHi,I have updated the code as per your requirement. Highlighted th.pdf
Hi,I have updated the code as per your requirement. Highlighted th.pdf
annaindustries
 
Consider this C++ BankAccount class with the following public member.pdf
Consider this C++ BankAccount class with the following public member.pdfConsider this C++ BankAccount class with the following public member.pdf
Consider this C++ BankAccount class with the following public member.pdf
archigallery1298
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
Thibaud Desodt
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
Programming Homework Help
 
Ch03
Ch03Ch03
Ch03
ojac wdaj
 
Ch03
Ch03Ch03
Please distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfPlease distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdf
neerajsachdeva33
 
Create a new Java project and add the Account class into the source co.pdf
Create a new Java project and add the Account class into the source co.pdfCreate a new Java project and add the Account class into the source co.pdf
Create a new Java project and add the Account class into the source co.pdf
admin618513
 
Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)
Chris Richardson
 
T4
T4T4
T4
lksoo
 
Inheritance
InheritanceInheritance
Inheritance
Young Alista
 
Inheritance
InheritanceInheritance
Inheritance
Harry Potter
 

Similar to Inheritance (20)

The java class Account that simultes the Account class.pdf
   The java class Account that simultes  the Account class.pdf   The java class Account that simultes  the Account class.pdf
The java class Account that simultes the Account class.pdf
 
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdfAccount.h  Definition of Account class. #ifndef ACCOUNT_H #d.pdf
Account.h Definition of Account class. #ifndef ACCOUNT_H #d.pdf
 
Class
ClassClass
Class
 
OOP: Classes and Objects
OOP: Classes and ObjectsOOP: Classes and Objects
OOP: Classes and Objects
 
Banks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdfBanks offer various types of accounts, such as savings, checking, cer.pdf
Banks offer various types of accounts, such as savings, checking, cer.pdf
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
 
In Visual Studios C# console app using multiple class files create a.pdf
In Visual Studios C# console app using multiple class files create a.pdfIn Visual Studios C# console app using multiple class files create a.pdf
In Visual Studios C# console app using multiple class files create a.pdf
 
I need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdfI need help creating a basic and simple Java program. Here is the ex.pdf
I need help creating a basic and simple Java program. Here is the ex.pdf
 
Hi,I have updated the code as per your requirement. Highlighted th.pdf
Hi,I have updated the code as per your requirement. Highlighted th.pdfHi,I have updated the code as per your requirement. Highlighted th.pdf
Hi,I have updated the code as per your requirement. Highlighted th.pdf
 
Consider this C++ BankAccount class with the following public member.pdf
Consider this C++ BankAccount class with the following public member.pdfConsider this C++ BankAccount class with the following public member.pdf
Consider this C++ BankAccount class with the following public member.pdf
 
Dependency injection - the right way
Dependency injection - the right wayDependency injection - the right way
Dependency injection - the right way
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Ch03
Ch03Ch03
Ch03
 
Ch03
Ch03Ch03
Ch03
 
Please distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdfPlease distinguish between the .h and .cpp file, create a fully work.pdf
Please distinguish between the .h and .cpp file, create a fully work.pdf
 
Create a new Java project and add the Account class into the source co.pdf
Create a new Java project and add the Account class into the source co.pdfCreate a new Java project and add the Account class into the source co.pdf
Create a new Java project and add the Account class into the source co.pdf
 
Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)Improving application design with a rich domain model (springone 2007)
Improving application design with a rich domain model (springone 2007)
 
T4
T4T4
T4
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 

More from FALLEE31188

Lecture4
Lecture4Lecture4
Lecture4
FALLEE31188
 
Lecture2
Lecture2Lecture2
Lecture2
FALLEE31188
 
L16
L16L16
L2
L2L2
Inheritance
InheritanceInheritance
Inheritance
FALLEE31188
 
Functions
FunctionsFunctions
Functions
FALLEE31188
 
Field name
Field nameField name
Field name
FALLEE31188
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
FALLEE31188
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
FALLEE31188
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
FALLEE31188
 
Chapter14
Chapter14Chapter14
Chapter14
FALLEE31188
 
Chapt03
Chapt03Chapt03
Chapt03
FALLEE31188
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
FALLEE31188
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
FALLEE31188
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
FALLEE31188
 
Brookshear 06
Brookshear 06Brookshear 06
Brookshear 06
FALLEE31188
 
Book ppt
Book pptBook ppt
Book ppt
FALLEE31188
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
FALLEE31188
 
Assignment
AssignmentAssignment
Assignment
FALLEE31188
 

More from FALLEE31188 (20)

Lecture4
Lecture4Lecture4
Lecture4
 
Lecture2
Lecture2Lecture2
Lecture2
 
L16
L16L16
L16
 
L2
L2L2
L2
 
Inheritance
InheritanceInheritance
Inheritance
 
Functions
FunctionsFunctions
Functions
 
Field name
Field nameField name
Field name
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Cis068 08
Cis068 08Cis068 08
Cis068 08
 
Chapter14
Chapter14Chapter14
Chapter14
 
Chapt03
Chapt03Chapt03
Chapt03
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
C++ polymorphism
C++ polymorphismC++ polymorphism
C++ polymorphism
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C1320prespost
C1320prespostC1320prespost
C1320prespost
 
Brookshear 06
Brookshear 06Brookshear 06
Brookshear 06
 
Book ppt
Book pptBook ppt
Book ppt
 
Assignment 2
Assignment 2Assignment 2
Assignment 2
 
Assignment
AssignmentAssignment
Assignment
 

Recently uploaded

RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
Wahiba Chair Training & Consulting
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 

Recently uploaded (20)

RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience How to Create a More Engaging and Human Online Learning Experience
How to Create a More Engaging and Human Online Learning Experience
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 

Inheritance

  • 1. CSC 222: Computer Programming II Spring 2005 Inheritance derived class, parent class inheriting fields & methods, overriding fields and methods bank account example IS-A relationship, polymorphism super methods, super constructor 1 Inheritance inheritance is a mechanism for enhancing existing classes one of the most powerful techniques of object-oriented programming allows for large-scale code reuse with inheritance, you can derive a new class from an existing one automatically inherit all of the fields and methods of the existing class only need to add fields and/or methods for new functionality example: • savings account is a bank account with interest • checking account is a bank account with transaction fees 2
  • 2. BankAccount class public class BankAccount { private double balance; private int accountNumber; private static int nextNumber = 1; here is an implementation of a public BankAccount() basic BankAccount class { balance = 0; accountNumber = nextNumber; nextNumber++; stores account number and } current balance public int getAccountNumber() { return accountNumber; uses static field to assign each } account a unique number public double getBalance() { accessor methods provide access } return balance; to account number and balance public void deposit(double amount) { deposit and withdraw methods balance += amount; allow user to update the balance } public void withdraw(double amount) { if (amount >= balance) { balance -= amount; } } } 3 Specialty bank accounts now we want to implement SavingsAccount and CheckingAccount a savings account is a bank account with an associated interest rate, interest is calculated and added to the balance periodically could copy-and-paste the code for BankAccount, then add a field for interest rate and a method for adding interest a checking account is a bank account with some number of free transactions, with a fee charged for subsequent transactions could copy-and-paste the code for BankAccount, then add a field to keep track of the number of transactions and a method for deducting fees disadvantages of the copy-and-paste approach tedious work lots of duplicate code – code drift is a distinct possibility if you change the code in one place, you have to change it everywhere or else lose consistency (e.g., add customer name to the bank account info) limits polymorphism (will explain later) 4
  • 3. SavingsAccount class inheritance provides a better solution can define a SavingsAccount to be a special kind of BankAccount automatically inherit common features (balance, account #, deposit, withdraw) simply add the new features specific to a savings account need to store interest rate, provide method for adding interest to the balance general form for inheritance: public class DERIVED_CLASS extends EXISTING_CLASS { ADDITIONAL_FIELDS ADDITIONAL_METHODS } public class SavingsAccount extends BankAccount { private double interestRate; note: the derived class public SavingsAccount(double rate) does not explicitly list { fields/methods from the } interestRate = rate; existing class (a.k.a. parent public void addInterest() class) – they are inherited { and automatically double interest = getBalance()*interestRate/100; deposit(interest); accessible } } 5 Using inheritance BankAccount generic = new BankAccount(); // creates bank account with 0.0 balance ... generic.deposit(120.0); // adds 120.0 to balance ... generic.withdraw(20.0); // deducts 20.0 from balance ... System.out.println(generic.getBalance()); // displays current balance: 100.0 SavingsAccount passbook = new SavingsAccount(3.5);// creates savings account, 3.5% interest ... passbook.deposit(120.0); // calls inherited deposit method ... passbook.withdraw(20.0); // calls inherited withdraw method ... System.out.println(passbook.getBalance()); // calls inherited getBalance method ... passbook.addInterest(); // calls new addInterest method ... System.out.println(passbook.getBalance()); // displays 103.5 6
  • 4. CheckingAccount class public class CheckingAccount extends BankAccount { can also define a class that private int transactionCount; private static final int NUM_FREE = 3; models a checking account private static final double TRANS_FEE = 2.0; again, inherits basic features public CheckingAccount() { of a bank account transactionCount = 0; assume some number of free } transactions public void deposit(double amount) after that, each transaction { super.deposit(amount); entails a fee transactionCount++; } must override the deposit and public void withdraw(double amount) withdraw methods to also { super.withdraw(amount); keep track of transactions transactionCount++; } can call the versions from the public void deductFees() parent class using super { if (transactionCount > NUM_FREE) { double fees = super.PARENT_METHOD(); TRANS_FEE * (transactionCount – NUM_FREE); super.withdraw(fees); } transactionCount = 0; } } 7 Interfaces & inheritance recall that with interfaces can have multiple classes that implement the same interface can use a variable of the interface type to refer to any object that implements it Comparable c1 = new String("foo"); Comparable c2 = new Integer(5); can use the interface type for a parameter, pass any object that implements it public void DoSomething(Comparable c) { . . . } --------------------------------------------- DoSomething("foo"); DoSomething(5); // note: 5 is autoboxed into an Integer the same capability holds with inheritance could assign a SavingsAccount object to a variable of type BankAccount could pass a CheckingAccount object to a method with a BankAccount parameter 8
  • 5. IS-A relationship the IS-A relationship holds when inheriting an object of the derived class is still an object of the parent class anywhere an object of the parent class is expected, can provide a derived object consider a real-world example of inheritance: animal classification ANIMAL FISH MAMMAL BIRD CARP GOLDFISH DOG CAT HUMAN DUCK BLUEJAY 9 Polymorphism in our example a SavingsAccount is-a BankAccount (with some extra functionality) a CheckingAccount is-a BankAccount (with some extra functionality) whatever you can do to a BankAccount (e.g., deposit, withdraw), you can do with a SavingsAccount or Checking account • derived classes can certainly do more (e.g., addInterest for SavingsAccount) • derived classes may do things differently (e.g., deposit for CheckingAccount) polymorphism: the same method call can refer to different methods when called on different objects the compiler is smart enough to call the appropriate method for the object BankAccount acc1 = new SavingsAccount(4.0); BankAccount acc2 = new CheckingAccount(); acc1.deposit(100.0); // calls the method defined in BankAccount acc2.deposit(100.0); // calls the method defined in CheckingAccount allows for general-purpose code that works on a class hierarchy 10
  • 6. import java.util.ArrayList; public class AccountAdd { Example use public static void main(String[] args) { SavingsAccount xmasFund = new SavingsAccount(2.67); xmasFund.deposit(250.0); SavingsAccount carMoney = new SavingsAccount(1.8); carMoney.deposit(100.0); note: in addToAll, the CheckingAccount living = new CheckingAccount(); appropriate deposit living.deposit(400.0); method is called on living.withdraw(49.99); each BankAccount ArrayList<BankAccount> finances = new ArrayList<BankAccount>(); finances.add(xmasFund); (depending on finances.add(carMoney); whether it is really a finances.add(living); SavingsAccount or addToAll(finances, 5.0); showAll(finances); CheckingAccount) } private static void addToAll(ArrayList<BankAccount> accounts, double amount) { for (int i = 0; i < accounts.size(); i++) { accounts.get(i).deposit(amount); } } private static void showAll(ArrayList<BankAccount> accounts) { for (int i = 0; i < accounts.size(); i++) { System.out.println(accounts.get(i).getAccountNumber() + ": $" + accounts.get(i).getBalance()); } } } 11 In-class exercise define the BankAccount, SavingsAccount, and CheckingAccount classes create objects of each class and verify their behaviors are account numbers consecutive regardless of account type? should they be? what happens if you attempt to withdraw more than the account holds? is it ever possible to have a negative balance? 12
  • 7. Another example: colored dice public class Die { we already have a class that models private int numSides; private int numRolls; a simple (non-colored) die can extend that class by adding a color public Die(int sides) field and an accessor method { numSides = sides; need to call the constructor for the Die numRolls = 0; class to initialize the numSides and } numRolls fields public int roll() { super(ARGS); numRolls++; return (int)(Math.random()*numSides) + 1; } public class ColoredDie extends Die { public int getNumSides() private String dieColor; { return numSides; public ColoredDie(int sides, String color) } { super(sides); public int getNumRolls() dieColor = color; { } return numRolls; } public String getColor() } { return dieColor; } } 13 ColoredDie example import java.util.ArrayList; import java.util.Collections; public class RollGame { consider a game in which private ArrayList<ColoredDie> dice; private static final int NUM_DICE = 5; you roll a collection of dice public RollGame() and sum their values { dice = new ArrayList<ColoredDie>(); dice.add(new ColoredDie(6, "red")); there is one "bonus" red die for (int i = 1; i < NUM_DICE; i++) { that counts double } dice.add(new ColoredDie(6, "white")); Collections.shuffle(dice); } public int rollPoints() { int total = 0; for (int i = 0; i < NUM_DICE; i++) { int roll = dice.get(i).roll(); if (dice.get(i).getColor().equals("red")) { total += 2*roll; } else { total += roll; } } return total; } } 14
  • 8. GridWorld GridWorld is a graphical environment under development by Cay Horstmann based on the AP Marine Biology Case Study can place actors in a Grid and have them move around and interact 15 Downloading the GridWorld download www.creighton.edu/~davereed/csc222/Code/GridWorld.zip you can store the file anywhere, e.g., the Desktop extract all of the files start up BlueJ, select Open Project and browse to select GridWorld call the main method of the CritterDemo class the initial grid has a Rock and a Critter can click on the Step button to see one move of the Critter (Rocks don't move) can click on the Run button to see repeated moves can also click on a grid space to add a Rock or Critter 16
  • 9. GridWorld base classes Grid<T>: an interface that defines a 2-dimensional grid of objects BoundedGrid<T>: a class that implements Grid<T>, using a 2-D array UnboundedGrid<T>: a class that implements Grid<T>, using a Map (later) Location: a class that encapsulates a location (row, col) on the Grid Actor: class that defines a generic actor that can move around a Grid public int getDirection() public Color getColor() public void setColor(Color newColor) public void turn(int angle) public Location move(Location loc, Grid<Actor> gr) public void act(Location loc, Grid<Actor> gr) act method is empty for Actor must define a class that inherits from Actor, overrides act to behave as desired 17 Rock class a rock is an actor that does nothing! must override the move method so that the rock can't move must override the setColor method since all rocks are black public class Rock extends Actor { // rocks don't move, so just returns current location public Location move(Location loc, Grid env) { return loc; } // rocks are always black, so disable any color change public void setColor(Color newColor) { // does nothing } } 18
  • 10. Critter class a Critter is an animal that scurries around the grid if clear, it will move in its current direction if blocked, it will turn 135 degrees to the right (backwards diagonal) public class Critter extends Actor { public Critter() { setColor(Color.GREEN); } public Critter(Color color) { setColor(color); } public void act(Location loc, Grid<Actor> gr) { Location newLoc = move(loc, gr); if (loc.equals(newLoc)) { turn(135); // if didn't move, then turn } } } 19 Other actors can define other Actor classes that define different behaviors Destroyer class moves similarly to Critter, but destroys any object it comes in contact with uses Grid method getAllNeighborLocations to get surrounding locations can then check each location to see if empty – if not, then remove contents can inherit from previously defined classes to modify behaviors FastCritter class moves similarly to Critter, but moves two steps instead of one since derived from Critter, could be used anywhere a Critter is expected other actors? 20