ClassDesignIIIAdvancedInheritance

上传人:xx****x 文档编号:240562360 上传时间:2024-04-15 格式:PPT 页数:36 大小:175KB
收藏 版权申诉 举报 下载
ClassDesignIIIAdvancedInheritance_第1页
第1页 / 共36页
ClassDesignIIIAdvancedInheritance_第2页
第2页 / 共36页
ClassDesignIIIAdvancedInheritance_第3页
第3页 / 共36页
资源描述:

《ClassDesignIIIAdvancedInheritance》由会员分享,可在线阅读,更多相关《ClassDesignIIIAdvancedInheritance(36页珍藏版)》请在装配图网上搜索。

1、Class Design III:Advanced InheritanceAdditional References“Object-Oriented Software Development Using Java”,Xiaoping Jia,Addison Wesley,2002“Core Java 2”,Cay Hortsmann,Gary Cornell,Sun Microsystems Press,2003You should be able to:describe the open-closed principle,why it matters,and how it applies t

2、o object-oriented code.use overloading correctly and recognize inappropriate uses describe the Liskov Substitution Principle(LSP)explain whether or not a given design adheres to the LSP incorporate inheritance into the design of software systems so that the LSP is respected compare and contrast the

3、use of inheritance and delegation use delegation and interfaces to realize multiple inheritance in design(e.g.,to support the implementation of multiple types)identify elements of a given design that violate the basic design principles of low coupling and high cohesionBackground:class member visibil

4、itypublic:Other classes can access these classes,fields,or methodsprivate:Only the declaring class can access these classes,fields,or methodsprotected:The declaring class and all sub-classes can access these classes fields,or methodspackage protected:Other classes in the same package can access thes

5、e classes,fields or methodsThis is the default visibility,when no keyword is used Class Design III:Good/Bad Practices3To Overload or Not to OverloadOverloading:Same name is used for more than one method in the same classMainly used for convenienceMisuse may reduce program readabilityShould use overl

6、oading only in two situations:There is a general description that fits all overloaded methods All overloaded methods have the same functionality(some may provide default arguments)Class Design III:Good/Bad Practices4To Overload or Not to OverloadOverloading:Same name is used for more than one method

7、 in the same classMainly used for convenienceMisuse may reduce program readabilityShould use overloading only in two situations:There is a general description that fits all overloaded methods All overloaded methods have the same functionality(some may provide default arguments)Class Design III:Good/

8、Bad Practices5Overloading ExamplesGood:Bad:class StringBuffer StringBuffer append(char c)StringBuffer append(int i)StringBuffer append(float f)class Employee /sets employees name void name(String s)/returns employees name String name()Do both fit under a common description?Class Design III:Good/Bad

9、Practices6Method Dispatch:Find the right method declaration for a given method call.METHOD CALLobject.methodCallName(arg1,arg2,.,argN)METHOD DECLARATIONreturnType declaredMethodName(parm1,parm2,.,parmN).Overall strategy:1.Find candidate method signatures(FindSignature)2.Use the most specific candida

10、te signature found(FindMostSpecific)3.Find a method matching that signature in the most specific class(FindMethod)Class Design III:Good/Bad Practices7Method Dispatch:Which method signatures are candidates?FindSignature1.In the reference type(i.e.static type)of the target object,select the set of met

11、hod signatures where.Declared name matches called method nameNumber of declared parameters matches number of actual arguments passed to method call2.From this set,restrict the set to those where.The reference type(i.e.static type)of each passed argument,matches or is a subtype of the corresponding p

12、arameter in a declared method signatureClass Design III:Good/Bad Practices8Method Dispatch:Which exact method signature will the target method have?FindMostSpecific1.From the candidates,select the one signature whose declared parameter types are furthest from Object in the inheritance hierarchyThese

13、 types are said to be the most specific2.In the case that some types are more specific for some parameters in a signature,but less specific for some parametersCompile time error,i.e.Java will not allow thisClass Design III:Good/Bad Practices9Method Dispatch:Which method with that signature is execut

14、ed?FindMethod1.Take the signature identified in FindMostSpecificDont worry about which class it came from or which method implementation was associated with the signature2.Now,select the class for the actual(runtime)type of the object the method is being called on(i.e.the target object).3.If that cl

15、ass has a method exactly matching the right method signature,execute that method,else repeat for super-class,etc.etc.Class Design III:Good/Bad Practices10Overloading Examplepublic class Employee public void name(String s)public void name(Object o)In Main:String stringAsString=new String(“aString”);O

16、bject stringAsObject=stringAsString;Employee e=new Employee();e.name(stringAsObject);/what gets called?e.name(stringAsString);/what gets called?Class Design III:Good/Bad Practices11Open-Closed PrincipleClasses should be open for extension but closed for modificationWant to extend the behaviour of ou

17、r system by adding subclasseswithout having to modify the superclassesThe principle suggests you should consider possible future subclasses when defining a classClass Design III:Good/Bad Practices12is-a Style Inheritance:The right wayIn addition to the required Java inheritance declaration(extends),

18、subclasses must logically be a subtype of supertype based on class contractLiskov Substitution Principle or LSPA subclass can weaken the preconditions“A subclass can require less restrictions”“A subclass can accept a larger range of values”A subclass can strengthen the postconditions“A subclass can

19、provide more guarantees”“A subclass can return a smaller range of values”Class Design III:Good/Bad Practices13is-a Style Inheritance:The right way Program should be able to use cars without having to know exactly which kind of car it is:void navigateToDestination(Car c)c.turnLeft();.CarturnLeft():vo

20、idturnRight():voidHybridCarHummerClass Design III:Good/Bad Practices14Weakening the preconditionA subclass method can weaken the precondition(but it cannot strengthen it)when overriding a method from its superclass.The subclass can accept a wider range of values as input.class Payment/*pre amt=0*/vo

21、id setPaymentAmount(int amt)class CreditCardPayment extends Payment/*pre true*/void setPaymentAmount(int amt)class CashPayment extends Payment Class Design III:Good/Bad Practices15Weakening the preconditionWhy does it not make sense to strengthen the precondition?Suppose we set the precondition on t

22、he setPaymentAmount of CreditCardPayment to be:pre amt=25Client should be able to do:Payment p;/substitute CashPayment for Payment p=new CashPayment();p.setPaymentAmount(5);./substitute CreditCardPayment for Payment p=new CreditCardPayment();p.setPaymentAmount(5);/oops!Class Design III:Good/Bad Prac

23、tices16Strengthening the postconditionA subclasss method can strengthen the postcondition(but it cannot weaken it):a subclasss method can return a subset of the values returned by the method it overrides.class Payment/*post returns=0*/double getInterest()class CreditCardPayment extends Payment/*post

24、 return 4.25*/double getInterest()class CashPayment extends Payment Class Design III:Good/Bad Practices17Strengthening the postconditionWhy does it not make sense to weaken the postcondition?Suppose the client writes code based on the postcondition of the superclass.That client code could break if w

25、e substitute a superclass object with an instance of one of its subclasses if the subclass method has a weaker postcondition.Example:client writes code assuming that a method returns a value that is positivesubclass overrides method to return*any*value(so postcondition is weakened)client code is goi

26、ng to break if a negative value is returned.Class Design III:Good/Bad Practices18Limitation Inheritance:The wrong waySubclass restricts rather than extends the behavior inherited from the superclassViolates is-a relationshipViolates the Liskov Substitution PrincipleUsually used for implementation co

27、nvenience(obviously in the wrong way)ExampleSquare defined as a subclass of Rectangle (next slide)Methods setHeight and setWidth are not applicable to a squareClass Design III:Good/Bad Practices19Example:Rectangle Classclass Rectangle private double height;/class invariant height0private double widt

28、h;/class invariant width0Rectangle(double h,double w)height=h;width=w;void setHeight(double h)height=h;void setWidth(double w)width=w;Class Design III:Good/Bad Practices20.double area()return height*width;Example:Rectangle Class(continued)Class Design III:Good/Bad Practices21Example:Square Class(the

29、 wrong way)class Square extends Rectangle Square()super();Square(double s)super(s,s);.What is wrong with this?Class Design III:Good/Bad Practices22 ./Override setHeight and setWidthvoid setHeight(double l)?void setWidth(double l)?void setSide(double s)super.setHeight(s);super.setWidth(s);Example:Squ

30、are Class(the wrong way,cont.)Class Design III:Good/Bad Practices23Example:Rectangle Class(revised)class NewRectangle protected double height;/class invariant height0protected double width;/class invariant width0Rectangle(double h,double w)height=h;width=w;double getArea()return height*width;Class D

31、esign III:Good/Bad Practices24Example:Square Class(a correct way)class NewSquare extends NewRectangle NewSquare(double s)super(s,s);void setSides(double s)height=s;width=s;Class Design III:Good/Bad Practices25Delegation another form of re-useA method delegates the execution of a task to another obje

32、ct of a different typeThink of the“other object”as a servant used to carry out the taskIn OO languages delegation can be:-class-based(or static)servant is a component of the classmethod-based(or dynamic)method creates a servant and delegates the serviceExample next slide:Square defined using class b

33、ased delegation Class Design III:Good/Bad Practices26Square Class(a right way)public class Square private Rectangle rectangle;public Square()rectangle=new Rectangle();public Square(double s)rectangle=new Rectangle(s,s);Class Design III:Good/Bad Practices27public void setSide(double s)rectangle.growT

34、oWidth(s);public double area()return rectangle.area();Square Class(a right way)Class Design III:Good/Bad Practices28Multiple InheritanceMultiple inheritance occurs when a class has more than one super-class.Multiple inheritance is supported by some programming languages(e.g.,C+)but not others(e.g.,J

35、ava).Multiple inheritance can lead to problems,for example,the classic diamond problem:StudentEmployeeTeachingAssistantPersonSuppose Person has a method myMethod()thats overridden in a different way in Student and Employee and thats not overridden in TeachingAssistant.Which version of the method sho

36、uld the following code call:TeachingAssistant ta=new TeachingAssistant();ta.myMethod();Class Design III:Good/Bad Practices29Handling Multiple Inheritance in JavaWe can use delegation to implement multiple class inheritance if necessaryFor instance:instead of this:you can do this:StudentEmployeeTeach

37、ingAssistantTeachingAssistantStudentInterfaceEmployeeInterfaceEmployeeStudentClass Design III:Good/Bad Practices30Multiple Inheritance Exampleinterface StudentInterface public float getGPA();interface EmployeeInterface public float getSalary();public class Student implements StudentInterface protect

38、ed float GPA;public float getGPA()/code for GPA Class Design III:Good/Bad Practices31public class Employee implements EmployeeInterface protected float salary;public float getSalary()/code for Salarypublic class TeachingAssistant implements StudentInterface,EmployeeInterface private Student student;

39、private Employee employee;Multiple Inheritance Example(continued)Class Design III:Good/Bad Practices32Multiple Inheritance Example(continued)public TeachingAssistant()student=new Student();employee=new Employee();public float getGPA()return student.getGPA();public float getSalary()return employee.ge

40、tSalary();Class Design III:Good/Bad Practices33Name Collisions Among InterfacesA Java class may extend another class and implement one or more interfacesInherited method from one interface may have same name as a method in another class or interfaceName Collision procedure:if methods have different

41、signatures,they are considered overloadedif they have same signature and return type,they are one methodif they have same signature,different return types,produce compilation errorif they have same signature and return type,but throw different exceptions,they are one method that throws the union of

42、the exceptions thrown by each of themClass Design III:Good/Bad Practices34General Design Guidelines for InheritancePlace common attributes and methods in the superclassesUse inheritance to model only is-a type relationshipsUse abstract classes and interfaces to design extensible families of objects

43、with common propertiese.g.,employees of different typese.g.,different types of objects to be drawn in a CAD applicationClass Design III:Good/Bad Practices35ExerciseWhich is the right way to define ellipse and circle?Ellipse+setMajorAxis(double):void+setMinorAxis(double):voidCircle+setRadius(double):

44、voidEllipse+setMajorAxis(double):void+setMinorAxis(double):voidCircle+setRadius(double):voidClass Design III:Good/Bad Practices36Key Concepts In This LectureThere are a lot of related concepts we covered in this lectureWhen you design a superclass,think about whether it might be extended in the futu

45、re(i.e.,which methods should be protected instead of private,etc.).This is the open-closed principle in action.In Java,a subclass is considered a subtype as is an implementation of an interface.To ensure an instance of a subclass(or a class that extends an interface)is substitutable for its supercla

46、ss(or its interface)we need to follow the Liskov Substitutability Principle(LSP).i.e.,watch out that pre-conditions and post-conditions of overridden methods do the right thing.If we want to reuse code but cant do it via a subclass because wed violate the LSP,we can use delegation where we keep an object of the type from which we want the code and we call the objects methods to do the work we want done.If we want one class to include behavior from different types,use interfaces(and sometimes delegation too!)

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!