Date post: | 04-Jan-2016 |
Category: |
Documents |
Upload: | josephine-hicks |
View: | 218 times |
Download: | 5 times |
Chapter 12 Advanced Chapter 12 Advanced InheritanceInheritance
Jim BurnsJim Burns
Creating and Using Abstract Creating and Using Abstract ClassesClasses
Child classes are more specific than their Child classes are more specific than their parentsparents
When you create a child class, it inherits all the When you create a child class, it inherits all the general attributes you needgeneral attributes you need
Thus you must create only the new, more Thus you must create only the new, more specific attributesspecific attributes
Superclasses contain the features that are Superclasses contain the features that are shared by their subclassesshared by their subclasses For example, the members of the For example, the members of the DogDog class are class are
shared by the shared by the PoodlePoodle and and Spaniel Spaniel subclassessubclasses
Parent classes…Parent classes…
Are sometimes so general that you never Are sometimes so general that you never intend to create any specific instances of intend to create any specific instances of the classthe class
An An abstract classabstract class is one from which you is one from which you cannot create any concrete instantiations, cannot create any concrete instantiations, but from which you can inheritbut from which you can inherit
Abstract classes usually have one or more Abstract classes usually have one or more empty abstract methodsempty abstract methods
Abstract ClassesAbstract Classes
You use the keyword ______ when you You use the keyword ______ when you declare an abstract classdeclare an abstract class
Abstract methodsAbstract methods
Have no body…Have no body…No braces, and no method statements.No braces, and no method statements.When you create an abstract method, you use When you create an abstract method, you use
the keyword _____the keyword _____
public abstract class Animalpublic abstract class Animal{{
private String nameOfAnimal;private String nameOfAnimal;public abstract void speak();public abstract void speak();public String getAnimalName()public String getAnimalName(){{
return nameOfAnimal;return nameOfAnimal;
}}public void setAnimalName(String name)public void setAnimalName(String name){{
nameOfAnimal = name;nameOfAnimal = name;
}}
}}
Note…Note…
If you declare any method to be an If you declare any method to be an abstract method, you must also declare its abstract method, you must also declare its class to be _______.class to be _______.
For ____ classesFor ____ classes
You cannot place a statement such asYou cannot place a statement such asAnimal myPet = new Animal(“Murphy”);Animal myPet = new Animal(“Murphy”);
You create an You create an abstractabstract class such as class such as Animal only so you can extend it.Animal only so you can extend it.
Example of extending an abstract classExample of extending an abstract classpublic class Dog extends Animalpublic class Dog extends Animal{{
public void speak()public void speak(){{
System.out.println(“Woof!”);System.out.println(“Woof!”);
}}
}}The speak() method within the Dog class The speak() method within the Dog class
is required because the abstract, parent is required because the abstract, parent Animal class contains an abstract speak() Animal class contains an abstract speak() method. You can code any statements method. You can code any statements you want within the Dog speak() method.you want within the Dog speak() method.
Public class Cow extends animalPublic class Cow extends animal
{{
public void speak()public void speak()
{{
System.out.println(“Moo!”);System.out.println(“Moo!”);
}}
}}
THE COW CLASSTHE COW CLASS
Public class Snake extends animalPublic class Snake extends animal
{{
public void speak()public void speak()
{{
System.out.println(“Ssss!”);System.out.println(“Ssss!”);
}}
}}
THE SNAKE CLASSTHE SNAKE CLASS
public class UseAnimalspublic class UseAnimals{{ public static void main(String[] args)public static void main(String[] args) {{ Dog myDog = new Dog();Dog myDog = new Dog(); Cow myCow = new Cow();Cow myCow = new Cow(); Snake mySnake = new Snake();Snake mySnake = new Snake(); myDog.setAnimalName("My dog Murphy");myDog.setAnimalName("My dog Murphy"); myCow.setAnimalName("My cow Elsie");myCow.setAnimalName("My cow Elsie"); mySnake.setAnimalName("My snake Sammy");mySnake.setAnimalName("My snake Sammy"); System.out.print(myDog.getAnimalName() + " says ");System.out.print(myDog.getAnimalName() + " says "); myDog.speak();myDog.speak(); System.out.print(myCow.getAnimalName() + " says ");System.out.print(myCow.getAnimalName() + " says "); myCow.speak();myCow.speak(); System.out.print(mySnake.getAnimalName() + " says ");System.out.print(mySnake.getAnimalName() + " says "); mySnake.speak();mySnake.speak(); }}}}
The above code produces the The above code produces the following at the command prompt:following at the command prompt:
C:\Java>java UseAnimalsC:\Java>java UseAnimalsMy dog Murphy says Woof!My dog Murphy says Woof!My cow Elsie says Moo!My cow Elsie says Moo!My snake Sammy says Ssss!My snake Sammy says Ssss!
C:\Java>C:\Java>
Using Dynamic Method BindingUsing Dynamic Method Binding
An instantiation of a subclass “is a” An instantiation of a subclass “is a” superclass object. superclass object.
Every SalariedEmployee “is an” employee; Every SalariedEmployee “is an” employee; every Dog “is an” animalevery Dog “is an” animal
The opposite is not true—an Animal is not The opposite is not true—an Animal is not a Doga Dog
Because every subclass object “is a” Because every subclass object “is a” superclass member, you can convert superclass member, you can convert subclass objects to superclass objectssubclass objects to superclass objects
More on dynamic method bindingMore on dynamic method binding Even though you cannot instantiate any objects Even though you cannot instantiate any objects
of an abstract class, you can indirectly create a of an abstract class, you can indirectly create a referencereference to a superclass abstract object to a superclass abstract object
A reference is not an object, but it points to a A reference is not an object, but it points to a memory addressmemory address
When you create a reference, you do not use When you create a reference, you do not use the keyword new; instead, you create a variable the keyword new; instead, you create a variable name in which you can hold the memory name in which you can hold the memory address of a concrete objectaddress of a concrete object
Even though a reference to an abstract Even though a reference to an abstract superclass object is not concrete, you can store superclass object is not concrete, you can store a reference to a concrete subclass object therea reference to a concrete subclass object there
An example of the use of referenceAn example of the use of reference
public class AnimalReferencepublic class AnimalReference{{ public static void main(String[] args)public static void main(String[] args) {{ Animal ref;Animal ref; ref = new Cow();ref = new Cow(); ref.speak();ref.speak(); ref = new Dog();ref = new Dog(); ref.speak();ref.speak(); }}}}
Recall from chapter 11…Recall from chapter 11…
That you can use the That you can use the instanceofinstanceof keyword keyword to determine whether an object is an to determine whether an object is an instance of any class in its hierarchy.instance of any class in its hierarchy.
For example, using the For example, using the AnimalAnimal and and DogDog classes, both of the following are true if classes, both of the following are true if myPoodlemyPoodle is a dog object: is a dog object:
myPoodle instanceof AnimalmyPoodle instanceof AnimalmyPoodle instanceof DogmyPoodle instanceof Dog
Polymorphic behaviorPolymorphic behavior
The example above demonstrates The example above demonstrates polymorphic behaviorpolymorphic behavior
After the variable After the variable refref is assigned an is assigned an address, the address, the ref.speak()ref.speak() method calls the method calls the correct correct speak()speak() method method
An application’s ability to select the correct An application’s ability to select the correct subclass method is known as subclass method is known as dynamic dynamic method bindingmethod binding
When the application executes, the correct When the application executes, the correct method is attached to the application method is attached to the application based on the current changing contentbased on the current changing content
Using a Superclass as a Method Using a Superclass as a Method ParameterParameter
Dynamic method binding is most useful when Dynamic method binding is most useful when you want to create a method that has one or you want to create a method that has one or more parameters that might be one of several more parameters that might be one of several typestypes
In the following, the header for the In the following, the header for the talkingAnimal()talkingAnimal() method in Figure 12-9 accepts method in Figure 12-9 accepts any type of any type of AnimalAnimal argument argument
The The talkingAnimal()talkingAnimal() method can be used in method can be used in programs that contain programs that contain DogDog objects, objects, CowCow objects objects or objects of any class that descends from or objects of any class that descends from AnimalAnimal
public class TalkingAnimalDemopublic class TalkingAnimalDemo{{ public static void main(String[] args)public static void main(String[] args) {{ Dog dog = new Dog();Dog dog = new Dog(); Cow cow = new Cow();Cow cow = new Cow(); dog.setAnimalName("Ginger");dog.setAnimalName("Ginger"); cow.setAnimalName("Molly");cow.setAnimalName("Molly"); talkingAnimal(dog);talkingAnimal(dog); talkingAnimal(cow);talkingAnimal(cow); }} public static void talkingAnimal(Animal animal)public static void talkingAnimal(Animal animal) {{ System.out.println("Come one come all");System.out.println("Come one come all"); System.out.println("See the amazing talking animal!");System.out.println("See the amazing talking animal!"); System.out.println(animal.getAnimalName() + " says");System.out.println(animal.getAnimalName() + " says"); animal.speak();animal.speak(); System.out.println("***************");System.out.println("***************"); }}}}
The above code produces the The above code produces the following at the command prompt:following at the command prompt:
C:\Java>java TalkingAnimalDemoC:\Java>java TalkingAnimalDemoCome one come allCome one come allSee the amazing talking animal!See the amazing talking animal!Ginger saysGinger saysWoof!Woof!********************************Come one come allCome one come allSee the maxing talking animal!See the maxing talking animal!Molly saysMolly saysMoo!Moo!**********************************
C:\Java>C:\Java>
Creating Arrays of Sublcass Creating Arrays of Sublcass ObjectsObjects
It can be convenient to create an array of generic It can be convenient to create an array of generic AnimalAnimal referencesreferences
An An AnimalAnimal array might contain individual elements that array might contain individual elements that are are DogDog, , CowCow, or , or SnakeSnake objects objects
The following statement creates an array of three Animal The following statement creates an array of three Animal referencesreferences
Animal[] ref = new Animal[3];Animal[] ref = new Animal[3]; This statement reserves enough computer memory for This statement reserves enough computer memory for
three three AnimalAnimal objects named objects named ref[0],ref[0], ref[1],ref[1], and and ref[2]ref[2] The statement does not actually instantiate The statement does not actually instantiate AnimalAnimals as s as
AnimalAnimals are abstracts are abstract
public class AnimalArrayDemopublic class AnimalArrayDemo{{ public static void main(String[] args)public static void main(String[] args) {{ Animal[] ref = new Animal[3];Animal[] ref = new Animal[3]; ref[0] = new Dog();ref[0] = new Dog(); ref[1] = new Cow();ref[1] = new Cow(); ref[2] = new Snake();ref[2] = new Snake(); for(int x = 0; x < 3; ++x)for(int x = 0; x < 3; ++x) ref[x].speak();ref[x].speak(); }}}}
The above code produces the The above code produces the following at the command prompt:following at the command prompt:
C:\Java>java AnimalArrayDemoC:\Java>java AnimalArrayDemo
Woof!Woof!
Moo!Moo!
Ssss!Ssss!
C:\Java>C:\Java>
Using the Object Class and Its Using the Object Class and Its MethodsMethods
The toString() MethodThe toString() MethodThe equals() MethodThe equals() Method
Using the Object Class and Its Using the Object Class and Its MethodsMethods
Every class in Java is actually a subclass, Every class in Java is actually a subclass, except oneexcept one
When you define a class, if you do not When you define a class, if you do not explicitly extend another class, your class explicitly extend another class, your class is an extension of the Object classis an extension of the Object class
The Object class is defined in the The Object class is defined in the java.lang package, which is imported java.lang package, which is imported automatically every time you write a automatically every time you write a program; it includes methods that you can program; it includes methods that you can use or override as you see fituse or override as you see fit
Using the Using the toString()toString() Method Method
The Object class The Object class toString()toString() method method converts an Object into a string that converts an Object into a string that contains information about the Objectcontains information about the Object
If you do not create a If you do not create a toString()toString() method for method for a class, you can use the superclass a class, you can use the superclass version of the version of the toString()toString() method method
public abstract class Animalpublic abstract class Animal{{ private String nameOfAnimal;private String nameOfAnimal; public abstract void speak();public abstract void speak(); public String getAnimalName()public String getAnimalName() {{ return nameOfAnimal;return nameOfAnimal; }} public void setAnimalName(String name)public void setAnimalName(String name) {{ nameOfAnimal = name;nameOfAnimal = name; }}}}public class Dog extends Animalpublic class Dog extends Animal{{ public void speak()public void speak() {{ System.out.println("Woof!");System.out.println("Woof!"); }}}}Public class DisplayDogPublic class DisplayDog{{
public static void main(String[ ] args)public static void main(String[ ] args){{
Dog myDog = new Dog();Dog myDog = new Dog();string dogString = myDog.toString();string dogString = myDog.toString();System.out.println(dogString);System.out.println(dogString);
}}}}
Public class DisplayDogPublic class DisplayDog{{
public static void main(String[ ] args)public static void main(String[ ] args){{
Dog myDog = new Dog();Dog myDog = new Dog();string dogString = myDog.toString();string dogString = myDog.toString();System.out.println(dogString);System.out.println(dogString);
}}}}
The above produces the following The above produces the following output at the command Promptoutput at the command Prompt
C:\Java>java DisplayDogC:\Java>java DisplayDog
Dog@19821fDog@19821f
C:\Java>C:\Java>
The output is the word Dog ‘at’ 19821f, The output is the word Dog ‘at’ 19821f, which is a hexadecimal number which is a hexadecimal number representing the referencerepresenting the reference
It is better to write your…It is better to write your…
own toString() method to override the one own toString() method to override the one supplied so you can, among other supplied so you can, among other purposes, debug a programpurposes, debug a program
The following example shows a The following example shows a BankAccount class that contains a mistake BankAccount class that contains a mistake in the pink linein the pink line
public class BankAccountpublic class BankAccount{{ private int acctNum;private int acctNum; private double balance;private double balance; public BankAccount(int num, double bal)public BankAccount(int num, double bal) {{ acctNum = num;acctNum = num; balance = num; // Mistake! Should be balance = balbalance = num; // Mistake! Should be balance = bal }} public String toString()public String toString() {{ String info = "BankAccount acctNum = " + acctNum +String info = "BankAccount acctNum = " + acctNum + " Balance = $" + balance;" Balance = $" + balance; return info;return info; }} public boolean equals(BankAccount secondAcct)public boolean equals(BankAccount secondAcct) {{ boolean result;boolean result; if(acctNum == secondAcct.acctNum &&if(acctNum == secondAcct.acctNum && balance == secondAcct.balance)balance == secondAcct.balance) result = true;result = true; elseelse result = false;result = false; return result;return result; }}
}}
public class TestBankAccountpublic class TestBankAccount{{ public static void main(String[] args)public static void main(String[] args) {{ BankAccount myAccount = new BankAccount myAccount = new
BankAccount(123, 4567.89);BankAccount(123, 4567.89); System.out.println(myAccount.toString());System.out.println(myAccount.toString()); }}}}
The above produces the following The above produces the following output at the Command Promptoutput at the Command Prompt
C:\Java>java TestBankAccountC:\Java>java TestBankAccount
BankAccount accNum = 123 BankAccount accNum = 123
Balance = $123.00Balance = $123.00
C:\JavaC:\Java
The advantage of using the The advantage of using the toString()toString()
toString()toString() is Java’s universal name for a is Java’s universal name for a method that converts an object’s relevant method that converts an object’s relevant details into details into StringString format format
As you use other programmers classes, As you use other programmers classes, you can hope that they have provided a you can hope that they have provided a toString()toString() method that provides output that method that provides output that you would want to see.you would want to see.
Using the Using the equals()equals() Method Method
The The ObjectObject class class equals()equals() method returns method returns a boolean value indicating whether the a boolean value indicating whether the objects are equalobjects are equal
if(someObject.equals(someOtherObjectOfThif(someObject.equals(someOtherObjectOfTheSameType)) system.out.println( “The eSameType)) system.out.println( “The objects are equal”);objects are equal”);
Two objects are equal only if they have the Two objects are equal only if they have the same memory addresssame memory address
public class CompareAccountspublic class CompareAccounts{{ public static void main(String[] args)public static void main(String[] args) {{ BankAccount acct1 = new BankAccount(1234, BankAccount acct1 = new BankAccount(1234,
500.00);500.00); BankAccount acct2 = new BankAccount(1234, BankAccount acct2 = new BankAccount(1234,
500.00);500.00); if(acct1.equals(acct2))if(acct1.equals(acct2)) System.out.println("Accounts are equal");System.out.println("Accounts are equal"); elseelse System.out.println("Accounts are not equal");System.out.println("Accounts are not equal"); }}}}
Command Prompt outputCommand Prompt output
C:\Java>java CompareAccountsC:\Java>java CompareAccounts
Accounts are not equalAccounts are not equal
C:\Java>C:\Java>
If you want two bank accounts…If you want two bank accounts…
To be equal if they have the same account To be equal if they have the same account number and balance, then you must write number and balance, then you must write your own your own equals()equals() method… method…
public class BankAccountpublic class BankAccount{{ private int acctNum;private int acctNum; private double balance;private double balance; public BankAccount(int num, double bal)public BankAccount(int num, double bal) {{ acctNum = num;acctNum = num; balance = num; // Mistake! Should be balance = balbalance = num; // Mistake! Should be balance = bal }} public String toString()public String toString() {{ String info = "BankAccount acctNum = " + acctNum +String info = "BankAccount acctNum = " + acctNum + " Balance = $" + balance;" Balance = $" + balance; return info;return info; }} public boolean equals(BankAccount secondAcct)public boolean equals(BankAccount secondAcct) {{ boolean result;boolean result; if(acctNum == secondAcct.acctNum &&if(acctNum == secondAcct.acctNum && balance == secondAcct.balance)balance == secondAcct.balance) result = true;result = true; elseelse result = false;result = false; return result;return result; }}
}}
Example of your own Example of your own equals()equals()
public boolean equals(BankAccount secondAcct)public boolean equals(BankAccount secondAcct) {{ boolean result;boolean result; if(acctNum == secondAcct.acctNum &&if(acctNum == secondAcct.acctNum && balance == secondAcct.balance)balance == secondAcct.balance) result = true;result = true; elseelse result = false;result = false; return result;return result; }}
Command Prompt outputCommand Prompt output
C:\Java>java CompareAccountsC:\Java>java CompareAccounts
Accounts are equalAccounts are equal
C:\Java>C:\Java>
Using Inheritance to Achieve Good Using Inheritance to Achieve Good Software DesignSoftware Design
When new car models are created, not When new car models are created, not every feature and function is redesigned every feature and function is redesigned from scratchfrom scratch
With inheritance, you can reuse existing With inheritance, you can reuse existing superclasses to create good designs superclasses to create good designs quicklyquickly
Advantages of InheritanceAdvantages of Inheritance
Subclass creators save development time Subclass creators save development time because much of the code needed for the because much of the code needed for the class has already been writtenclass has already been written
Subclass creators save testing time Subclass creators save testing time because the superclass code has already because the superclass code has already been tested and used in a variety of been tested and used in a variety of situationssituations
More advantages…More advantages…
Programmers who create or use new Programmers who create or use new subclasses already understand how the subclasses already understand how the superclass works, so the time it takes to superclass works, so the time it takes to learn the new class features is reducedlearn the new class features is reduced
When you create a new subclass in Java, When you create a new subclass in Java, neither the superclass source code nor the neither the superclass source code nor the superclass bytecode is changedsuperclass bytecode is changed
Creating and Using InterfacesCreating and Using Interfaces
Some programming languages like C++ Some programming languages like C++ allow for a subclass to inherit from more allow for a subclass to inherit from more than one superclassthan one superclass
The ability to inherit from more than one The ability to inherit from more than one class is called class is called multiple inheritancemultiple inheritance
Multiple inheritance is a difficult concept—Multiple inheritance is a difficult concept—to which superclass should to which superclass should supersuper refer to? refer to?
Sooo, multiple inheritance is disallowed in Sooo, multiple inheritance is disallowed in JavaJava
InterfacesInterfaces
Java provides an alternative to multiple Java provides an alternative to multiple inheritance—an inheritance—an InterfaceInterface
An interface looks much like a class, except that An interface looks much like a class, except that all of its methods are implicitly all of its methods are implicitly publicpublic and and abstractabstract, and all of its data items are implicitly , and all of its data items are implicitly publicpublic, , staticstatic and and finalfinal
When you create a class that uses an interface, When you create a class that uses an interface, you include the keyword implements and the you include the keyword implements and the interface name in the class headerinterface name in the class header
This notation requires class objects to include This notation requires class objects to include code for every method in the interface that has code for every method in the interface that has been implementedbeen implemented
More on InterfacesMore on Interfaces
Whereas using Whereas using extendsextends allows a subclass allows a subclass to use nonprivate, nonoverriden members to use nonprivate, nonoverriden members of its parent’s class, of its parent’s class, implementsimplements requires requires the subclass to implement its own version the subclass to implement its own version of each method in the interfaceof each method in the interface
In the following, a In the following, a workerworker interface is interface is defined that contains the single method defined that contains the single method called called work()work()
When any class implements When any class implements workerworker, it , it must also include a must also include a work()work() method method
Public abstract class animalPublic abstract class animal{{
private String nameOfAnimal;private String nameOfAnimal;public abstract void speak();public abstract void speak();public String getAnimalName()public String getAnimalName(){{
return nameOfanimal;return nameOfanimal;}}public void setAnimalName(String name)public void setAnimalName(String name){{
nameOfanimal = name;nameOfanimal = name;}}
}}Public class Dog extends AnimalPublic class Dog extends Animal{{
public void speak()public void speak(){{
System.out.println(“woof!”);System.out.println(“woof!”);}}
}}Public interface WorkerPublic interface Worker{{
public void work();public void work();}}
public class WorkingDog extends Dog implements Workerpublic class WorkingDog extends Dog implements Worker{{ private int hoursOfTraining;private int hoursOfTraining; public void setHoursOfTraining(int hrs)public void setHoursOfTraining(int hrs) {{ hoursOfTraining = hrs;hoursOfTraining = hrs; }} public int getHoursOfTraining()public int getHoursOfTraining() {{ return hoursOfTraining;return hoursOfTraining; }} public void work()public void work() {{ speak();speak(); System.out.println("I am a dog who works");System.out.println("I am a dog who works"); System.out.println("I have " + hoursOfTraining +System.out.println("I have " + hoursOfTraining + " hours of professional training!");" hours of professional training!"); }}}}
public class DemoWorkingDogspublic class DemoWorkingDogs{{ public static void main(String[] args)public static void main(String[] args) {{ WorkingDog aSheepHerder = new WorkingDog();WorkingDog aSheepHerder = new WorkingDog(); WorkingDog aSeeingEyeDog = new WorkingDog();WorkingDog aSeeingEyeDog = new WorkingDog(); aSheepHerder.setAnimalName("Simon, the Border Collie");aSheepHerder.setAnimalName("Simon, the Border Collie"); aSeeingEyeDog.setAnimalName("Sophie, the German Shepherd");aSeeingEyeDog.setAnimalName("Sophie, the German Shepherd"); aSheepHerder.setHoursOfTraining(40);aSheepHerder.setHoursOfTraining(40); aSeeingEyeDog.setHoursOfTraining(300);aSeeingEyeDog.setHoursOfTraining(300); System.out.println(aSheepHerder.getAnimalName() + " says ");System.out.println(aSheepHerder.getAnimalName() + " says "); aSheepHerder.speak();aSheepHerder.speak(); aSheepHerder.work();aSheepHerder.work(); System.out.println();System.out.println(); System.out.println(aSeeingEyeDog.getAnimalName() + " says ");System.out.println(aSeeingEyeDog.getAnimalName() + " says "); aSeeingEyeDog.speak();aSeeingEyeDog.speak(); aSeeingEyeDog.work();aSeeingEyeDog.work(); }}}}
Command Prompt outputCommand Prompt outputC:\Java>java demoWorkingDogsC:\Java>java demoWorkingDogsSimon, the Border Collie saysSimon, the Border Collie saysWoof!Woof!Woof!Woof!I am a dog who worksI am a dog who worksI have 40 hours of professional training!I have 40 hours of professional training!
Sophie, the German Shepherd saysSophie, the German Shepherd saysWoof!Woof!Woof!Woof!I am a dog who worksI am a dog who worksI have 300 hours of professional training!I have 300 hours of professional training!
C:\Java>C:\Java>
More on InterfacesMore on Interfaces
Abstract classes and interfaces are similar in Abstract classes and interfaces are similar in that you cannot instantiate concrete objects from that you cannot instantiate concrete objects from either oneeither one
Abstract classes differe from interfaces because Abstract classes differe from interfaces because abstract classes can contain nonabstract abstract classes can contain nonabstract methods, but all methods within and interface methods, but all methods within and interface must be abstract.must be abstract.
A class can inherit from only one abstract A class can inherit from only one abstract superclass, but it can implement any number of superclass, but it can implement any number of iterfacesiterfaces
Creating Interfaces to Store Creating Interfaces to Store Related ConstantsRelated Constants
Interfaces can contain data fields, but the Interfaces can contain data fields, but the must be public, static and finalmust be public, static and final
The purpose in creating an interface The purpose in creating an interface containing constants is to provide a set of containing constants is to provide a set of data that a number of classes can use data that a number of classes can use without having to re-declare the valueswithout having to re-declare the values
An example followsAn example follows
public interface PizzaConstantspublic interface PizzaConstants {{ public static final int SMALL_DIAMETER = 12;public static final int SMALL_DIAMETER = 12; public static final int LARGE_DIAMETER = 16;public static final int LARGE_DIAMETER = 16; public static final double TAX_RATE = 0.07;public static final double TAX_RATE = 0.07; public static final String COMPANY = public static final String COMPANY =
"Antonio's Pizzeria";"Antonio's Pizzeria"; }}
public class PizzaDemo implements PizzaConstantspublic class PizzaDemo implements PizzaConstants {{ public static void main(String[] args)public static void main(String[] args) {{ double specialPrice = 11.25;double specialPrice = 11.25; System.out.println("Welcome to " + COMPANY);System.out.println("Welcome to " + COMPANY); System.out.println("We are having a special offer:\na System.out.println("We are having a special offer:\na
" +" + SMALL_DIAMETER + " inch pizza with four SMALL_DIAMETER + " inch pizza with four
ingredients\nor a " +ingredients\nor a " + LARGE_DIAMETER + " inch pizza with one LARGE_DIAMETER + " inch pizza with one
ingredient\nfor only $" +ingredient\nfor only $" + specialPrice);specialPrice); System.out.println("With tax, that is only $" +System.out.println("With tax, that is only $" + (specialPrice + specialPrice * TAX_RATE));(specialPrice + specialPrice * TAX_RATE)); }} }}
Command Prompt outputCommand Prompt outputC:\Java>javaPizzaDemoC:\Java>javaPizzaDemo
Welcome to Antonio’s PizzeriaWelcome to Antonio’s Pizzeria
We are having a special offer:We are having a special offer:
A 12 inch pizza with four ingredientsA 12 inch pizza with four ingredients
Or a 16 inch pizza with one ingredientOr a 16 inch pizza with one ingredient
For only $11.25For only $11.25
With tax, that is only $12.0375With tax, that is only $12.0375
C:\Java>C:\Java>
Creating and Using PackagesCreating and Using Packages
You know how to import packages into your You know how to import packages into your programsprograms
Java.lang package is automatically imported into Java.lang package is automatically imported into every program your writeevery program your write
A A packagepackage is a named collection of classes is a named collection of classes When you create your own classes, you can When you create your own classes, you can
place them in packages so that you can easily place them in packages so that you can easily import related classes into new programsimport related classes into new programs
More on packagesMore on packages
Creating packages encourages others to Creating packages encourages others to reuse software because it makes it reuse software because it makes it convenient to import many related classes convenient to import many related classes at onceat once
When you create classes for others to use, When you create classes for others to use, you do not want to provide the users with you do not want to provide the users with your source code in the files with .java your source code in the files with .java extensionsextensions
So you compile your classesSo you compile your classes
You are creating compiled classes with the You are creating compiled classes with the .class extensions.class extensions
The .class files are the files you place in a The .class files are the files you place in a package so other programmers can import package so other programmers can import themthem
You include a package statement at the You include a package statement at the beginning of your class file to place the beginning of your class file to place the compiled code into the indicated foldercompiled code into the indicated folder
The package statementThe package statement
package com.course.animals;package com.course.animals;
Indicates that the compiled file should be placed in Indicates that the compiled file should be placed in a folder named com.course.animalsa folder named com.course.animals
The compiled program goes into an animals folder The compiled program goes into an animals folder within the course folder within the com folderwithin the course folder within the com folder
The package statement should be the first such The package statement should be the first such statement and should be outside the class statement and should be outside the class definitiondefinition