1 / 22

The finalize , clone , and getClass Methods

Learn about finalize, clone, and getClass methods in Java. Understand object relationships, method invocations, superclass and subclass interactions. Discover abstract classes, inheritance models, and implementation cases. Dive into final methods and classes, and explore a payroll system using polymorphism.

Download Presentation

The finalize , clone , and getClass Methods

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Nice to know 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.

  2. Nice to know 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

  3. Relationships Among Objects in an Inheritance Hierarchy • If Circle is a subclass of Point, • Circle inherited from Point • Manipulate Point and Circle objects using their respective reference varibales to invoke methods • In fact, you can • 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. • Subclass method calls via superclass-type variables • Key concept • subclass object can be treated as superclass object • “is-a” relationship, however, • Superclass object is not always a subclass object

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

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

  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 ^ 1 error

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

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

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

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

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

  12. getArea getVolume getName print 0.0 pr2 0.0 0.0 = 0 = 0 "Circle" pr2h 0.0 0.0 [x,y] 2pr2 +2prh center=[x,y]; radius=r; height=h "Point" "Cylinder" Shape Point center=[x,y]; radius=r Circle Cylinder Case Study: Inheriting Interface and Implementation \case-study1

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

  14. Case Study: Payroll System Using Polymorphism • Create a payroll program • Use abstract methods and polymorphism • Problem statement • 4 types of employees, paid weekly • Salaried (fixed salary, no matter the hours) • Hourly (overtime [>40 hours] pays time and a half) • Commission (paid percentage of sales) • Base-plus-commission (base salary + percentage of sales) • Boss wants to raise pay by 10%

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

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

  17. Implementing Multiple Interface 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;} Case Study: Creating and Using Interfaces (Cont.) ..\..\week10\case-study4

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

  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. 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. Nice to know 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.

  22. Nice to know 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

More Related