Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.

Similar presentations


Presentation on theme: "1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The."— Presentation transcript:

1 1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The clone() method copies an object.  The getClass() method returns an instance of the java.lang.Class class, which contains the information about the class for the object. Before an object is created, its defining class is loaded and the JVM automatically creates an instance of java.lang.Class for the class. From this instance, you can discover the information about the class at runtime. Nice to know

2 2 The finalization Demo The finalize method is invoked by the JVM. You should never write the code to invoke it in your program. For this reason, the protected modifier is appropriate. FinalizationDemo Nice to know

3 3 Relationships Among Objects in an Inheritance Hierarchy  If Circle is a subclass of Point, Circle inherited from Point Circle inherited from Point Manipulate Point and Circle objects using their respective reference varibales to invoke methods Manipulate Point and Circle objects using their respective reference varibales to invoke methods  In fact, you can Invoking superclass methods from subclass objects Invoking superclass methods from subclass objects Assigning subclass object to superclass reference varibale, or sometimes, assigning object referenced by superclass type variable to a subclass type reference variables. Assigning subclass object to superclass reference varibale, or sometimes, assigning object referenced by superclass type variable to a subclass type reference variables. Subclass method calls via superclass-type variables Subclass method calls via superclass-type variables  Key concept subclass object can be treated as superclass object subclass object can be treated as superclass object “ is-a ” relationship, however,“ is-a ” relationship, however, Superclass object is not always a subclass object Superclass object is not always a subclass object

4 4 Invoking Superclass Methods from Subclass Objects Invoking Superclass Methods from Subclass Objects  Store references to superclass and subclass objects Assign a superclass object to superclass-type variable Assign a superclass object to superclass-type variable Assign a subclass object to a subclass-type variable Assign a subclass object to a subclass-type variable Both straightforwardBoth straightforward Assign a subclass object to a superclass variable Assign a subclass object to a superclass variable “ is a ” relationship“ is a ” relationship relationships_1relationships_1.java

5 5 Using Superclass Objects with Subclass-Type Variables  Previous example Assigned subclass object to superclass-type variable Assigned subclass object to superclass-type variable Circle “ is a ” PointCircle “ is a ” Point  Assign superclass object to subclass-type variable Compiler error Compiler error No “ is a ” relationshipNo “ is a ” relationship Point is not a CirclePoint is not a Circle Circle has data/methods that Point does notCircle has data/methods that Point does not setRadius (declared in Circle ) not declared in Point setRadius (declared in Circle ) not declared in Point Cast superclass references to subclass references Cast superclass references to subclass references Called downcastingCalled downcasting Invoke subclass functionalityInvoke subclass functionality

6 6 1 // HierarchyRelationshipTest2.java 2 // Attempt to assign a superclass reference to a subclass-type variable. 3 4 public class HierarchyRelationshipTest2 { 5 6 public static void main( String[] args ) 7 { 8 Point3 point = new Point3( 30, 50 ); 9 Circle4 circle; // subclass-type variable 10 11 // assign superclass reference to subclass-type variable 12 circle = point; // Error: a Point3 is not a Circle4 13 } 14 15 } // end class HierarchyRelationshipTest2 HierarchyRelationshipTest2.java:12: incompatible types found : Point3 required: Circle4 circle = point; // Error: a Point3 is not a Circle4 circle = point; // Error: a Point3 is not a Circle4 ^ 1 error

7 7 Subclass Method Calls via Superclass- Type variables  Call a subclass method with superclass reference Compiler error Compiler error Subclass methods are not superclass methodsSubclass methods are not superclass methods

8 8 Abstract Classes and Methods  Abstract classes Are superclasses (called abstract superclasses) Are superclasses (called abstract superclasses) Cannot be instantiated Cannot be instantiated Incomplete Incomplete subclasses fill in "missing pieces"subclasses fill in "missing pieces"  Concrete classes Can be instantiated Can be instantiated Implement every method they declare Implement every method they declare Provide specifics Provide specifics

9 9 Abstract Classes and Methods (Cont.)  Abstract classes not required, but reduce client code dependencies  To make a class abstract Declare with keyword abstract Declare with keyword abstract Contain one or more abstract methods Contain one or more abstract methods public abstract void draw(); Abstract methods Abstract methods No implementation, must be overriddenNo implementation, must be overridden

10 10 Case Study: Inheriting Interface and Implementation  Make abstract superclass Shape Abstract method (must be implemented) Abstract method (must be implemented) getName, printgetName, print Default implementation does not make senseDefault implementation does not make sense Methods may be overridden Methods may be overridden getArea, getVolumegetArea, getVolume Default implementations return 0.0 Default implementations return 0.0 If not overridden, uses superclass default implementationIf not overridden, uses superclass default implementation Subclasses Point, Circle, Cylinder Subclasses Point, Circle, Cylinder

11 11 Case Study: Inheriting Interface and Implementation Case Study: Inheriting Interface and Implementation Circle Cylinder Point Shape Fig. 10.4 Shape hierarchy class diagram.

12 12 Case Study: Inheriting Interface and Implementation 0.0 = 0 0.0 "Point"[x,y] pr2pr2 0.0"Circle" center=[x,y]; radius=r 2pr 2 +2prhpr2hpr2h "Cylinder" center=[x,y]; radius=r; height=h getAreaprintgetNamegetVolume Shape Point Circle Cylinder \case-study1

13 13 final Methods and Classes  final methods Cannot be overridden Cannot be overridden private methods are implicitly final private methods are implicitly final static methods are implicitly final static methods are implicitly final  final classes Cannot be superclasses Cannot be superclasses Methods in final classes are implicitly final Methods in final classes are implicitly final e.g., class String e.g., class String

14 14 Case Study: Payroll System Using Polymorphism Case Study: Payroll System Using Polymorphism  Create a payroll program Use abstract methods and polymorphism Use abstract methods and polymorphism  Problem statement 4 types of employees, paid weekly 4 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 of sales)Base-plus-commission (base salary + percentage of sales) Boss wants to raise pay by 10% Boss wants to raise pay by 10%

15 15 Case Study: Payroll System Using Polymorphism Case Study: Payroll System Using Polymorphism  Superclass Employee Abstract method earnings (returns pay) Abstract method earnings (returns pay) abstract because need to know employee typeabstract because need to know employee type Cannot calculate for generic employeeCannot calculate for generic employee Other classes extend Employee Other classes extend Employee Employee SalariedEmployeeHourlyEmployeeCommissionEmployee BasePlusCommissionEmployee \case-study2

16 16 Case Study: Creating and Using Interfaces Case Study: Creating and Using Interfaces  Use interface Shape Replace abstract class Shape Replace abstract class Shape  Interface Declaration begins with interface keyword Declaration begins with interface keyword Classes implement an interface (and its methods) Classes implement an interface (and its methods) Contains public abstract methods Contains public abstract methods Classes (that implement the interface) must implement these methodsClasses (that implement the interface) must implement these methods \case-study3

17 17 Case Study: Creating and Using Interfaces (Cont.) Case Study: Creating and Using Interfaces (Cont.)  Implementing Multiple Interface Provide common-separated list of interface names after keyword implements Provide common-separated list of interface names after keyword implements  Declaring Constants with Interfaces public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; } public interface Constants { public static final int ONE = 1; public static final int TWO = 2; public static final int THREE = 3; }..\..\week10\case-study4

18 18 Type-Wrapper Classes for Primitive Types  Type-wrapper class Each primitive type has one Each primitive type has one Character, Byte, Integer, Boolean, etc.Character, Byte, Integer, Boolean, etc. Enable to represent primitive as Object Enable to represent primitive as Object Primitive types can be processed polymorphicallyPrimitive types can be processed polymorphically Declared as final Declared as final Many methods are declared static Many methods are declared static Check API.

19 19 Hiding Fields and Static Methods You can override an instance method, but you cannot override a field (instance or static variables) or a static method. If you declare a field or a static method in a subclass with the same name as one in the superclass, the one in the superclass is hidden, but it still exists. The two fields or static methods are independent. You can reference the hidden field or static method using the super keyword in the subclass. The hidden field or method can also be accessed via a reference variable of the superclass ’ s type.

20 20 Hiding Fields and Static Methods, cont.  When invoking an instance method from a reference variable, the actual class of the object referenced by the variable decides which implementation of the method is used at runtime.  When accessing a field or a static method, the declared type of the reference variable decides which method is used at compilation time. HidingDemo

21 21 Initialization Block Initialization blocks can be used to initialize objects along with the constructors. An initialization block is a block of statements enclosed inside 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 the beginning of every constructor in the class. Nice to know

22 22 Static Initialization Block A static initialization block is much like a nonstatic initialization block except that it is declared static, can only refer to static members of the class, and is invoked when the class is loaded. The JVM loads a class when it is needed. A superclass is loaded before its subclasses. InitializationDemo Nice to know


Download ppt "1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The."

Similar presentations


Ads by Google