CS 884 (Prasad)Java Classes1 Classes Fields, methods, and constructors Inheritance.

Slides:



Advertisements
Similar presentations
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Advertisements

Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Inheritance Inheritance Reserved word protected Reserved word super
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2007.
OOP Languages: Java vs C++
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Cs3180 (Prasad)L8Packages1 Packages Organizing large programs => From monolithic programs to partitioning class name space Access control of names => Enforcing.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Implementation: Part 3 Software Construction Lecture 8.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance and Access Control CS 162 (Summer 2009)
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
CS 884 (Prasad)Java Names1 Names Scope and Visibility Access Control Packages.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance ndex.html ndex.htmland “Java.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
CS 3180 (Prasad)L67Classes1 Classes and Interfaces Inheritance Polymorphism.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Polymorphism in Methods
Modern Programming Tools And Techniques-I
Inheritance-Basics.
Inheritance and Polymorphism
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Java Inheritance.
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

CS 884 (Prasad)Java Classes1 Classes Fields, methods, and constructors Inheritance

CS 884 (Prasad)Java Classes2 Class Declaration Fields (Type + Field initializer) Class variables (static) Instance variables Methods ( Signature + Code) Class methods (static) Instance methods Static Initializers ( Code to initialize class vars) Constructors (Code to initialize instance vars) Initialization blocks

CS 884 (Prasad)Java Classes3 Method Declaration Formal parameter names are distinct and cannot be hidden. Actual arguments are passed by value. Method body is a block. Methods cannot be nested. (Mutual) Recursion is permitted. The body of a static (class) method can refer only to static members.

CS 884 (Prasad)Java Classes4 Subclass class Object is the root of class hierarchy. Subclass Members inherited(public/protected/default?) members inherited from direct super-class. inheritedmembers inherited from direct super-interface. members explicitly declared in the subclass. Constructors and static initializers are not inherited. Class with private constructors not instantiated. Default constructor for class C. – C( ) { super( ); }

CS 884 (Prasad)Java Classes5 Alternatives: when scopes overlap... Scopes of simple name x of members E1 and E2 overlap Overloading: Both E1 and E2 available. –If both are methods, use x if resolvable by signature. –If both are constant fields, use qualified names. If scope x/E2 included in scope x/E1, then Hiding: x refers to E2, but E1 exists and is accessible by a qualified name or super.x. Overriding: x refers to E2, and E1 does not exist. ( E1 in parent reusable using super.x. )

CS 884 (Prasad)Java Classes6 Field name conflicts Fields declared in a class must have distinct names. Fields declared in a class hide fields inherited (from the super-class or super-interfaces) with the same simple name. Instance (static) field can hide static (instance) field. Fields inherited with same simple name must be referred to using unambiguous names. Initialization: final fields, static fields, instance fields (in each catergory: textual order)

CS 884 (Prasad)Java Classes7 Design Issues class C { class SC extends C { TC x; TSC x;...}...} If field redefinition were banned, adding a “conflicting” field to C can invalidate SC. Thus, while updating a class, a programmer would have had to look into all the subclasses before choosing a name!

CS 884 (Prasad)Java Classes8 If overriding of fields were permitted, the methods in C could break, even if TSC were to be a subtype of TC. This is because type correctness of assignments can be violated. class C { TC x; TC y; TC p() { x = y; y = x; return x; } } class SC extends C { TSC x; } new SC().p(); ERROR: “x = y / y = x” unless TC has same type as entity !!!

CS 884 (Prasad)Java Classes9 In Java, type TSC and TC are unrelated, and subclass field x hides class field x. In languages such as C++, addition of a field in a parent class requires recompilation of subclasses because storage requirement for a subclass instance has changed. –In Ada, clients of a package need to be recompiled even when the private -section is modified because storage requirements might have changed. (Client code however remains unaltered.) –In Modula-2, clients are not recompiled because only reference types are used in this situation and storage requirements are fixed a priori.

CS 884 (Prasad)Java Classes10 Solving Fragile Superclass Problem The Java compiler passes symbolic references to members, while the interpreter performs final name resolution at link-time. The storage layout of objects is not determined by the compiler, but is deferred to run time and determined by the interpreter. Updated classes with new instance variables or methods can be linked in without affecting existing code.

CS 884 (Prasad)Java Classes11 Method name conflicts Method (Constructor) Signature name of the method number, type, and order of formal parameters Overloading: A class may not declare two methods with the same signature. A declared instance (resp. static) method overrides (resp. hides) an inherited instance (resp. static) method with the same signature. Compile-time Error: if an instance (static) method has same signature as an inherited static (instance) method.

CS 884 (Prasad)Java Classes12 Hidden/overidden members Compile-time Error: Two methods (declared or hidden or overridden) with same signature but different return types (or void ). – Simplifies overload-resolution. (Cf. Ada) S func(int x) {} neither overloads nor overrides T func(int x) {} if S =/= T. Hidden fields/ (static) methods can be accessed using a name or a cast to super-class type or using super. Overridden (instance) methods and parent constructors can be accessed only using super.

CS 884 (Prasad)Java Classes13 Inheritance A class inherits from its direct super- class and direct super-interfaces all the fields and methods (whether abstract or not) of the parents that are accessible to the code (e.g., protected, but not private ) and are neither overridden nor hidden by a declaration in the class.

CS 884 (Prasad)Java Classes14 A class can inherit two or more fields with the same name either from two interfaces or from its super-class and an interface. –Multiply inherited fields may be disambiguated using qualified names. Hidden fields and private fields are implemented by a subclass instance, that is, has storage allocated for it. Hidden/overridden members may be accessed in the subclass using qualified names or super. Private members declared in a class are not accessible in a subclass.

CS 884 (Prasad)Java Classes15 Overriding and Dynamic Binding class C { void p() {} } class S extends C { void p() {} } C x = new S(); x.p() Illegal Overloading and Overriding class C { void p() {} float p() {} } class S extends C { int p() {} }

CS 884 (Prasad)Java Classes16 Hiding and Overriding S x = new S(); C y = x; (x.a == 77) (y.a == 84) (((C) x).a == 84) (x.p() == y.p()) (((C)x).p() == y.p()) (x.q() != y.q()) (((C) x).q() == y.q()) class C { int a = 84; static int q() {} int p() {...} } class S extends C { int a = 77; static int q() { C.q();...} int p() {... super.p();...} }

CS 884 (Prasad)Java Classes17 Dynamic Binding When an instance method is invoked through an object reference, the actual class of the object governs which implementation is used. (In contrast, when a field or a static method is accessed, the declared type of the reference is used.

CS 884 (Prasad)Java Classes18 Binding and Type System

CS 884 (Prasad)Java Classes19 Dynamic Binding in Java class P { public void f(P p) { System.out.println("f(P) in P. "); } class C extends P { public void f(P p) { System.out.println("f(P) in C. "); } public void f(C cp) { System.out.println("f(C) in C. "); }

CS 884 (Prasad)Java Classes20 class DynamicBinding { public static void main(String[] args) { P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); }

CS 884 (Prasad)Java Classes21 Abbreviated Example class P { public void f(P p){} } class C extends P { public void f(P p){} public void f(C c){} } P pp = new P(); C cc = new C(); P pc = cc; pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc);

CS 884 (Prasad)Java Classes22 Compile-time vs Run-time (binding) pp.f(pp); pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pp); cc.f(cc); >=P f(P) {} (coercion) >=P f(P) {} (coercion) >=C f(P) {} >=C f(C) {} P f(P) {} (coercion) C f(P) {} (coercion) C f(P) {} C f(C) {}

CS 884 (Prasad)Java Classes23 Static binding of Signatures, Dynamic binding of Code class P { public void f(P p){System.out.println("f(P) in P. "); } } class C extends P { public void f(P p){System.out.println("f(P) in C. ");} public void f(C c){System.out.println("f(C) in C. "); } } class DYNAMIC2 { public static void main(String[] args) { P pp = new P(); C cc = new C(); P pc = cc; pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pc); cc.f(cc); ((P) cc).f(cc); ((P) cc).f((P) cc); }

CS 884 (Prasad)Java Classes24 Static binding of Signatures, Dynamic binding of Code class P { public void f(P p){System.out.println("f(P) in P. "); } public void f(C c){System.out.println("f(C) in P. "); } } class C extends P { public void f(P p){System.out.println("f(P) in C. ");} } class DYNAMIC { public static void main(String[] args) { P pp = new P(); C cc = new C(); P pc = cc; pp.f(cc); pc.f(pp); pc.f(cc); cc.f(pc); cc.f(cc); // Error: Java 5 ((P) cc).f(cc); ((P) cc).f((P) cc); }

CS 884 (Prasad)Java Classes25 Keywords : Abstract, Final final field = (constant declaration) ( requires initializer ). - final ref type field = ( fixed object, state changeable). final class method = ( subclass cannot hide ). final instance method = ( subclass cannot override). code for final methods can be in-lined. (no dynamic binding necessary) abstract class method = compile-time error. abstract instance method = ( no implementation).

CS 884 (Prasad)Java Classes26 (cont’d) An abstract method can override a non-abstract method. This forces subclasses to re-implement the latter. final class = (no subclass). abstract class = ( can contain abstract method). (cannot be instantiated). final and abstract = compile-time error. interface = (all fields final, all methods abstract).

CS 884 (Prasad)Java Classes27 Abstract Class Factors commonality for reuse : Framework. abstract class Sorters { abstract boolean compare ( Employee e1, Employee e2 ); public void sort( Employee [] ea) {... } } Subclasses: Sort_Increasing, Sort_Decreasing, Sort_on_Name, Sort_on_Age, Sort_on_Salary.

CS 884 (Prasad)Java Classes28 “Implementing” method An inherited (a declared) method from (in) super- class (class) implements/overrides methods with the same signature (multiply) inherited from super-interfaces. Methods are overridden on a signature-by- signature basis. The actual method executed when an instance method is invoked on an object is determined at run-time, using dynamic method lookup. Static method invocation is fixed at compile-time.

CS 884 (Prasad)Java Classes29 Classes : public vs non-public public classes are accessible outside the package using fully-qualified name or single- type-import declaration. non-public classes are not accessible. However, an instance of a non-public subclass (of a public class) may get assigned indirectly. However, a public field / method of a non- public subclass (of a public class) may be accessed / invoked indirectly through dynamic binding.

CS 884 (Prasad)Java Classes30 package points; public class Point { public int x, y; public void move(int dx, int dy) { x += dx; y += dy; } package morePoints; class Point3d extends points.Point { public int z; public void move(int dx,int dy,int dz){ super.move(dx, dy); z += dz; }

CS 884 (Prasad)Java Classes31 package morePoints; public class OnePoint { static points.Point getOne() { return new Point3d(); } in: package different: call: points.Point p = morePoints.OnePoint.getOne(); morePoints.OnePoint.getOne();

CS 884 (Prasad)Java Classes32 package morePoints; public class Point4d extends Point3d { public int w; public void move(int dx, int dy, int dz, int dw) { super.move(dx, dy, dz); w += dw; } in: package different: call: ( new Point4d() ).z ;

CS 884 (Prasad)Java Classes33 Other Implicit Constraints Access modifier of an hiding/overriding method must provide at least as much access as the hidden/overridden method. Otherwise, access barrier beaten by casting. An implementing/overriding method can throw only a subset of checked exceptions in the throws clause of overridden method. Otherwise, dynamic binding can defeat guarantees associated with checked exceptions.

CS 884 (Prasad)Java Classes34 Dynamic binding : Banned Access Control, Exceptions class C { public void p() {} int q() {} } class S extends C { private void p() {} int q() throws Exception {} } C x = new S(); x.p()

CS 884 (Prasad)Java Classes35 Constructors Modifiers Legal: public, protected, private Illegal: abstract, final, static In the absence of explicit constructor definition, a default no-argument constructor is supplied. this, super –Normally, this refers to the current object, and super to (compile-time) direct super- class.

CS 884 (Prasad)Java Classes36 (cont’d) this, super as constructor calls –In the first statement of a constructor body, this(…) invokes another constructor of the same class, and super(…) invokes a constructor of the direct super-class. Enables reuse of initialization code. Factoring common code. –In the absence of explicit constructor invocation (this(...)/super(...)), the default super(); is called.

CS 884 (Prasad)Java Classes37 Constructor Initialization Sequence When an object is created, all the fields are set to default values for their respective types before a constructor is invoked. Each constructor has three phases: –Invoke a super-class’s constructor. –Initialize the fields using their initializers and initialization blocks (in the order of appearance). –Execute the body of the constructor. Interaction with dynamic lookup : the body of an instance method can require a field before it is explicitly initialized.

CS 884 (Prasad)Java Classes38 class P3 { int m = 3; P3() {} void mag() {System.out.println(m);} } class C2 extends P3{ int n; C2() {m = 2; n = 2;} } In steady state, mag for P3-objects prints 3 and mag for C2-objects prints 2. Example: Transient field values

CS 884 (Prasad)Java Classes39 class P3 { int m = 3; P3() {mag();} void mag() {System.out.println(m);} } class C2 extends P3{ int n; C2() {m = 2; n = 2;} } When a P3-object or a C2-object is created, mag prints 3. (cont’d)

CS 884 (Prasad)Java Classes40 class P3 { int m = 3; P3() {mag();} void mag() {System.out.println(m);} } class C2 extends P3{ int n; C2() {m = 2; n = 2;} void mag() {System.out.println(m*n);} } When a C2-object is created, mag prints 0, even though in the steady state mag prints 4. (cont’d)

CS 884 (Prasad)Java Classes41 Transient field values (SKIP) class P3 { int m = 3; P3() {} P3() {int i = 5; mag(i);} void mag(int x) {x = m*x;} } class C2 extends P3{ int n; C2() {m = 2; n = 2;} void mag(int x) {x = m*n*x;} } mag for P3-objects (C2-objects) triples (doubles) its arg. However, if mag is invoked in P3(), on behalf of C2(), it triples, not doubles, its arg. If mag is now overridden in C2 to quadruple its arg, it actually zeros its arg when invoked in P3() for C2.

CS 884 (Prasad)Java Classes42 Protected Members: revisited The protected constructors / protected overridden methods of a class are accessible to its subclass (even outside the package) through super. The protected fields of a class are present in the instances of its subclass (even outside the package), and the protected methods are inherited. A protected member of a class can be accessed from a subclass (even outside the package) through an object reference that is at least the same type as the subclass.

CS 884 (Prasad)Java Classes43 Miscellaneous Wrapper ClassesWrapper Classes needed to make objects out of primitive types. Primitive types int, boolean, etc. associated with wrapper classes Integer, Boolean, etc. Marking methods and classes as final can improve security. validatePassword IsA relationship vs HasA relationship Dog IsA Mammal, Dog HasA Tail Square IsA Rectangle, Rectangle HasA Side

CS 884 (Prasad)Java Classes44 The reference type Object can be used to approximate parameterized types. Cf. Ada generics, C++ templates, ML’s polymorphic types. E.g., the utility classes such as Vector, Stack, etc can declare the type of element as Object, enabling them to be used for any instance. –Type casts are however needed to ensure type safety.

CS 884 (Prasad)Java Classes45 Further Updates Java 5: Autoboxing and unboxing Java 5: Generics