1 the finalize, clone, and getclass methods the finalize method is invoked by the garbage collector...
Post on 21-Jan-2016
238 Views
Preview:
TRANSCRIPT
11
The The finalizefinalize, , cloneclone, and , and getClassgetClass Methods Methods
The The finalizefinalize method is invoked by the garbage method is invoked by the garbage collector on an object when the object becomes collector on an object when the object becomes garbage. garbage.
The The clone()clone() method copies an object. method copies an object.
The The getClass()getClass() method returns an instance of the method returns an instance of the java.lang.Classjava.lang.Class class, which contains the information class, which contains the information about the class for the object. Before an object is about the class for the object. Before an object is created, its defining class is loaded and the JVM created, its defining class is loaded and the JVM automatically creates an instance of automatically creates an instance of java.lang.Classjava.lang.Class for for the class. From this instance, you can discover the the class. From this instance, you can discover the information about the class at runtime. information about the class at runtime.
Nice to knowNice to know
22
The The finalizationfinalization Demo Demo
The The finalizefinalize method is invoked by the JVM. method is invoked by the JVM. You should never write the code to invoke it You should never write the code to invoke it in your program. For this reason, the in your program. For this reason, the protected modifier is appropriate.protected modifier is appropriate.
FinalizationDemoFinalizationDemo
Nice to knowNice to know
33
Relationships Among Objects in an Inheritance Relationships Among Objects in an Inheritance HierarchyHierarchy
If Circle is a subclass of Point,If Circle is a subclass of Point, CircleCircle inherited from inherited from PointPoint Manipulate Manipulate PointPoint and and CircleCircle objects using their respective objects using their respective
reference varibales to invoke methodsreference varibales to invoke methods In fact, you canIn fact, you can
Invoking superclass methods from subclass objectsInvoking superclass methods from subclass objects Assigning subclass object to superclass reference varibale, or Assigning subclass object to superclass reference varibale, or
sometimessometimes, assigning object referenced by superclass type variable to , assigning object referenced by superclass type variable to a subclass type reference variables.a subclass type reference variables.
Subclass method calls via superclass-type variablesSubclass method calls via superclass-type variables Key conceptKey concept
subclass object can be treated as superclass objectsubclass object can be treated as superclass object
• ““is-a” relationship, however,is-a” relationship, however, Superclass object is not always a subclass objectSuperclass object is not always a subclass object
44
Invoking Superclass Methods from Invoking Superclass Methods from Subclass ObjectsSubclass Objects
Store references to superclass and subclass Store references to superclass and subclass objectsobjects Assign a superclass object to superclass-type variableAssign a superclass object to superclass-type variable Assign a subclass object to a subclass-type variableAssign a subclass object to a subclass-type variable
• Both straightforwardBoth straightforward Assign a subclass object to a superclass variableAssign a subclass object to a superclass variable
• ““is a” relationshipis a” relationship
relationships_1.java
55
Using Superclass Objects with Using Superclass Objects with Subclass-Type VariablesSubclass-Type Variables
Previous examplePrevious example Assigned subclass object to superclass-type variableAssigned subclass object to superclass-type variable
• CircleCircle “is a” “is a” PointPoint
Assign superclass object to subclass-type variableAssign superclass object to subclass-type variable Compiler errorCompiler error
• No “is a” relationshipNo “is a” relationship• PointPoint is not a is not a CircleCircle• CircleCircle has data/methods that has data/methods that PointPoint does not does not
setRadiussetRadius (declared in (declared in CircleCircle) not declared in ) not declared in PointPoint Cast superclass references to subclass referencesCast superclass references to subclass references
• Called downcastingCalled downcasting• Invoke subclass functionalityInvoke subclass functionality
66
1 // HierarchyRelationshipTest2.java1 // HierarchyRelationshipTest2.java2 // Attempt to assign a superclass reference to a subclass-type 2 // Attempt to assign a superclass reference to a subclass-type variable.variable.3 3 4 public class HierarchyRelationshipTest2 { 4 public class HierarchyRelationshipTest2 { 5 5 6 public static void main( String[] args ) 6 public static void main( String[] args ) 7 {7 {8 Point3 point = new Point3( 30, 50 );8 Point3 point = new Point3( 30, 50 );9 Circle4 circle; // subclass-type variable9 Circle4 circle; // subclass-type variable10 10 11 // assign superclass reference to subclass-type variable11 // assign superclass reference to subclass-type variable12 circle = point; // Error: a Point3 is not a Circle4 12 circle = point; // Error: a Point3 is not a Circle4 13 }13 }14 14 15 } // end class HierarchyRelationshipTest215 } // end class HierarchyRelationshipTest2
HierarchyRelationshipTest2.java:12: incompatible typesHierarchyRelationshipTest2.java:12: incompatible types
found : Point3found : Point3
required: Circle4required: Circle4
circle = point; // Error: a Point3 is not a Circle4circle = point; // Error: a Point3 is not a Circle4
^̂
1 error1 error
77
Subclass Method Calls via Superclass-Subclass Method Calls via Superclass-Type variablesType variables
Call a subclass method with superclass Call a subclass method with superclass referencereference Compiler errorCompiler error
• Subclass methods are not superclass methodsSubclass methods are not superclass methods
88
Abstract Classes and MethodsAbstract Classes and Methods Abstract classes Abstract classes
Are superclasses (called abstract superclasses)Are superclasses (called abstract superclasses) Cannot be instantiated Cannot be instantiated IncompleteIncomplete
• subclasses fill in "missing pieces"subclasses fill in "missing pieces"
Concrete classesConcrete classes Can be instantiatedCan be instantiated Implement every method they declareImplement every method they declare Provide specificsProvide specifics
99
Abstract Classes and Methods Abstract Classes and Methods (Cont.)(Cont.)
Abstract classes not required, but reduce Abstract classes not required, but reduce client code dependenciesclient code dependencies
To make a class abstractTo make a class abstract Declare with keyword Declare with keyword abstractabstract Contain one or more Contain one or more abstract methodsabstract methods
public abstract void draw();public abstract void draw(); Abstract methodsAbstract methods
• No implementation, must be overriddenNo implementation, must be overridden
1010
Case Study: Inheriting Interface Case Study: Inheriting Interface and Implementationand Implementation
Make abstract superclass Make abstract superclass ShapeShape Abstract method (must be implemented)Abstract method (must be implemented)
• getNamegetName, , printprint• Default implementation does not make senseDefault implementation does not make sense
Methods may be overriddenMethods may be overridden• getAreagetArea, , getVolumegetVolume
Default implementations return Default implementations return 0.00.0
• If not overridden, uses superclass default If not overridden, uses superclass default implementationimplementation
Subclasses Subclasses PointPoint, , CircleCircle, , CylinderCylinder
1111
Case Study: Inheriting Interface and Case Study: Inheriting Interface and ImplementationImplementation
Circle
Cylinder
Point
Shape
Fig. 10.4 Shape hierarchy class diagram.
1212
Case Study: Inheriting Interface and Case Study: Inheriting Interface and ImplementationImplementation
0.0 0.0 = 0 = 0
0.0 0.0 "Point" [x,y]
pr2 0.0 "Circle" center=[x,y]; radius=r
2pr2 +2prh pr2h "Cylinder"center=[x,y]; radius=r; height=h
getArea printgetNamegetVolume
Shape
Point
Circle
Cylinder
\case-study1
1313
finalfinal Methods and Classes Methods and Classes
finalfinal methods methods Cannot be overriddenCannot be overridden privateprivate methods are implicitly methods are implicitly finalfinal staticstatic methods are implicitly methods are implicitly finalfinal
finalfinal classes classes Cannot be superclassesCannot be superclasses Methods in Methods in finalfinal classes are implicitly classes are implicitly finalfinal
e.g., class e.g., class StringString
1414
Case Study: Payroll System Case Study: Payroll System Using PolymorphismUsing Polymorphism
Create a payroll programCreate a payroll program Use abstract methods and polymorphismUse abstract methods and polymorphism
Problem statementProblem statement 4 types of employees, paid weekly4 types of employees, paid weekly
• Salaried (fixed salary, no matter the hours)Salaried (fixed salary, no matter the hours)• Hourly (overtime [>40 hours] pays time and a half)Hourly (overtime [>40 hours] pays time and a half)• Commission (paid percentage of sales)Commission (paid percentage of sales)• Base-plus-commission (base salary + percentage Base-plus-commission (base salary + percentage
of sales)of sales) Boss wants to raise pay by 10%Boss wants to raise pay by 10%
1515
Case Study: Payroll System Using Case Study: Payroll System Using PolymorphismPolymorphism
Superclass Superclass EmployeeEmployee Abstract method Abstract method earningsearnings (returns pay) (returns pay)
• abstract abstract becausebecause need to know employee type need to know employee type• Cannot calculate for generic employeeCannot calculate for generic employee
Other classes extend Other classes extend EmployeeEmployee
Employee
SalariedEmployee HourlyEmployeeCommissionEmployee
BasePlusCommissionEmployee
\case-study2
1616
Case Study: Creating and Case Study: Creating and Using InterfacesUsing Interfaces
Use Use interfaceinterface ShapeShape Replace Replace abstractabstract class class ShapeShape
InterfaceInterface Declaration begins with Declaration begins with interfaceinterface keyword keyword Classes Classes implementimplement an interface (and its an interface (and its
methods)methods) Contains Contains publicpublic abstractabstract methods methods
• Classes (that Classes (that implementimplement the interface) must the interface) must implement these methodsimplement these methods
\case-study3
1717
Case Study: Creating and Case Study: Creating and Using Interfaces (Cont.)Using Interfaces (Cont.)
Implementing Multiple InterfaceImplementing Multiple Interface Provide common-separated list of interface Provide common-separated list of interface
names after keyword names after keyword implementsimplements Declaring Constants with InterfacesDeclaring Constants with Interfaces
public interface Constants {public interface Constants { public static final int ONE = 1; public static final int ONE = 1; public static final int TWO = 2; public static final int TWO = 2; public static final int THREE = public static final int THREE = 3;3;}}
..\..\week10\case-study4
1818
Type-Wrapper Classes for Type-Wrapper Classes for Primitive TypesPrimitive Types
Type-wrapper classType-wrapper class Each primitive type has oneEach primitive type has one
• CharacterCharacter, , ByteByte, , IntegerInteger, , BooleanBoolean, etc., etc. Enable to represent primitive as Enable to represent primitive as ObjectObject
• Primitive types can be processed polymorphicallyPrimitive types can be processed polymorphically Declared as Declared as finalfinal Many methods are declared Many methods are declared staticstatic
Check API.Check API.
1919
Hiding Fields and Static MethodsHiding Fields and Static MethodsYou can override an instance method, but you You can override an instance method, but you cannot override a field (instance or static cannot override a field (instance or static variables) or a static method. If you declare a field variables) or a static method. If you declare a field or a static method in a subclass with the same or a static method in a subclass with the same name as one in the superclass, the one in the name as one in the superclass, the one in the superclass is hidden, but it still exists. The two superclass is hidden, but it still exists. The two fields or static methods are independent. You can fields or static methods are independent. You can reference the hidden field or static method using reference the hidden field or static method using the the supersuper keyword in the subclass. The hidden keyword in the subclass. The hidden field or method can also be accessed via a field or method can also be accessed via a reference variable of the superclass’s type.reference variable of the superclass’s type.
2020
Hiding Fields and Static Methods, cont.Hiding Fields and Static Methods, cont.
When invoking an instance method from a reference When invoking an instance method from a reference variable, variable, the actual classthe actual class of the object referenced by of the object referenced by the variable decides which implementation of the the variable decides which implementation of the method is used at runtime.method is used at runtime.
When accessing a field or a static method, When accessing a field or a static method, the the declared typedeclared type of the reference variable decides which of the reference variable decides which method is used at compilation time. method is used at compilation time.
HidingDemoHidingDemo
2121
Initialization BlockInitialization BlockInitialization blocks can be used to initialize objects along with the Initialization blocks can be used to initialize objects along with the constructors. An initialization block is a block of statements enclosed inside constructors. An initialization block is a block of statements enclosed inside a pair of braces. An initialization block appears within the class declaration, a pair of braces. An initialization block appears within the class declaration, but not inside methods or constructors. It is executed as if it were placed at but not inside methods or constructors. It is executed as if it were placed at the beginning of every constructor in the class. the beginning of every constructor in the class.
public class Book { private static int numOfObjects; private String title; private int id; public Book(String title) { numOfObjects++; this.title = title; } public Book(int id) { numOfObjects++; this.id = id; } }
public class Book { private static int numOfObjects; private String title private int id; public Book(String title) { this.title = title; } public Book(int id) { this.id = id; } { numOfObjects++; } }
Equivalent
Nice to knowNice to know
2222
Static Initialization BlockStatic Initialization Block
A static initialization block is much like a A static initialization block is much like a nonstatic initialization block except that it is nonstatic initialization block except that it is declared declared staticstatic, can only refer to static , can only refer to static members of the class, and is invoked when members of the class, and is invoked when the class is loaded. The JVM loads a class the class is loaded. The JVM loads a class when it is needed. A superclass is loaded when it is needed. A superclass is loaded before its subclasses. before its subclasses.
InitializationDemoInitializationDemo
Nice to knowNice to know
top related