




已阅读5页,还剩4页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
SCJP Study Notes: Chapter 2 Object OrientationChapter 2 Object Orientation1. Encapsulation- keep instance var protected by using private- make public accessor method (getter and setter)2. Inheritance, IS-A, HAS-AEvery class in JAVA is a subclass of object classe.g. inherit equals, instanceof methodInheritance provide code reuse, polymorphism2.1 IS-Ao Through inheritance (extends)o Through implements (interface)e.g. BMW is-a Car BMW extends CarCar is-a Vehicle BMW is a vehicle (2 level)2.2 HAS-AClass A HAS-A B if code in Class A has a ref. to instance of Be.g. BMW IS A Car, BMW HAS-A Wheelpublic class BMW extends Car private Wheel myWheel;3. PolymorphismJava does NOT support multiple inheritancepublic interface Accelerable accelerate ( );class BMW extends Car implements AccelerableBMW can be treated polymorphically as:BMW bmw = new BMW( );Object O = bmw;Car car = bmw;Accelerable a = bmw;Car and bmw can invoke drive( ) method4. Overriding / Overloading4.1 Overridingwhen a class inherit method from superclass, have opportunity to override except that the method is marked finalpublic class TestCar public static void main(String args) Car a = new Car( );Car b = new BMW( ); / Car ref, BMW objecta.drive( ); / car versionb.drive( ); / bmw versionclass Car public void drive( ) / Overridden methodclass BMW extends Car public void drive( ) / Overriding methodpublic void accelerate Car c = new Car( );c.accelerate( ); / ERRORcompiler looks only at ref. type, NOT instance typeThe overriding method cannot have a more restrictive access modifier than the method being overriddene.g. drive( ) in BMW cant be private or protectedRules for overriding a method1. Arg. list must exactly match the overridden method, O.W. end up with overload2. return type must be the same as, or subtype of the return type declared in the original overridden method in the superclass3. access level cant be more restrictive than the overridden method4. access level CAN be LESS restrictive 5. Instance method can be overridden only if they are inherit by subclass6. the overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declare the exception7. the overriding method MUST NOT throw checked exception that are new or broader than those declared by the overridden methode.g. FileNotFoundException cant be overrided by SQLException8. the overriding method CAN throw narrower or fewer exception9. CANNOT override a method marked final, static10. if method cant inherited, cant override it, e.g. private method.Invoke superclass method super.drive( );e.g. public class Car public void drive ( ) Illegal Override:private void drive( ) public void drive( ) throws IOException public void drive(String speed) public String drive ( ) 4.2 Overloaded Method- let you reuse same method name, with diff. arg (optionally return type)Rules for Overload1. Overloaded method MUST change the arg. list2. Overloaded method CAN change the return type3. Overloaded method CAN change the access modifier4. Overloaded method CAN declare new or broader checked exception5. A method can be overloaded in the same class or in subclasse.g. public class Foo public void doStuff(int y, String s) class Bar extends Foo public void doStuff(int y, long s) throws IOException No problem, since overload, rather than overidee.g. public void changeSize(int size, String name, float pattern) Legal overload:public void changeSize(int size, String name) public int changeSize(float pattern, String name) throws IOExceptionInvoking overloaded method that take obj. ref.class Car class BMW extends Car class UseCar public void doStuff(Car c) / Car public void doStuff(BMW b) / BMW public static void main(String args) UseCar uc = new UseCar( );Car carObj = new Car( );BMW bmwObj = new BMW( );uc.doStuff(carObj);/ Caruc.doStuff(bmwObj);/ BMWCar carRefToBMW = new BMW( );uc.doStuff(carRefToBMW);O/P: Car signature of method is NOT dynamically decided at runtime, the ref. type NOT obj type determine which overloaded method is invokede.g. public class Car public void drive ( ) / Generic Car public class BMW extends Car public void drive ( ) / BMW (Override) public void drive (String s) / BMW + s (Overload) 1. Car c = new Car ( );/ Generic Carc.drive( );2. BMW b = new BMW( );/ BMWb.drive( );3.Car c = new BMW( );/ BMW polymorphismc.drive( );4. BMW b = new BMW( );/ BMW testb.drive(“test”);5. Car c = new Car ( );/ ERROR, car doesnt have drive(s)c.drive(“test”);6. Car c = new BMW( );/ ERROR, still look at Carc.drive(“test”);7. BMW b = new Car( );/ ERROROverload MethodOverridden MethodArgumentMust changeMust NOT changeReturn typeCan changeCant change except covariantExceptionCan changeCan reduce or eliminateAccess modifierCan changeMust NOT make more restrictiveInvocationRef. type determine which version Happen at compile timeObj. type, actual instanceDetermine at runtime5. Reference Variable CastingCar mycar = new BMW( );can be combined as(BMW)mycar).accelerate( );if(mycar instanceof BMW) BMW b = (BMW)mycar;b.accelerate( );Downcast casting down the inheritance tree to more specific classCar mycar = new Car( );BMW b = (BMW)mycar;/ compiles, but fail at runtimeString s = (String)mycar;/ compile failUpcast work implicitlysince BMW IS-A CarBMW b = new BMW( );Car c1 = b;Car c2 = (Car)b;6. Implementing an InterfaceWhen you implement an interface adhere to contract defined in interfaceNon Abstract implementation class must:1. provide concrete implementation for all method declared in the interface2. follow all the rule for legal override3. declare no checked exception on implementation method other than those declared by the interface method, or subclass of those declared by interface method4. maintain the signature of the interface method, same return typeAn implementation class can itself be abstract, no need to provide implementation, pass to its first concrete subclassabstract class Ball implements Bounceable class BaseBall extends Ballpublic void bounce( ) / implement Bounceable since it extend BallTwo more rules:1. A class implement more than one interfacepublic class Ball implements Bounceable, Serializable, subclassing define who and what you are, implementing define the role you can playe.g. Person extends Human, implement Programmer, Employee2. An interface can itself extend another interface, but never implement anythingpublic interface Bounceable extends Moveable The first concrete implementation class must implements all method of Bounceable + MoveableAn interface can extend MULTIPLE interfaceinterface Bounceable extends Moveable, Spherical class Foo class Bar implements Foo / ERROR, cant implement a classinterface Ba2 interface Fi interface Fee implements Ba2 / ERROR, cant implement an interfaceinteface Zee implements Foo / ERROR, cant implement a classinteface Zoo extends Foo / ERRORinterface Boo extends Fi / OKclass Toon extends Foo, Button / ERRORclass zoom implements Fi, Fee / OKinterface vroom extends Fi, Fee / OKclass Yow extends Foo implements Fi / OK, extends MUST be first7. Legal Return Types7.1 Return Type Declarationpublic class Foo void go( ) public class Bar extends FooString go(int x) return null;/ OK, overloadBut String go( );/ NOT OKFor Java5, can change return type in the overriding method as long as the new return type is a subtype of the declared return type of the overridden methodclass Alpha Alpha doStuff(char c ) return new Alpha( );class Beta extends Alpha/ OK in Java5Beta doStuff(char c)return new Beta( );7.2 Return a Value1. Can return nullpublic Button doStuff( ) return null;2. Can return arraypublic String go( ) return new String “a1”, “a2”; 3. For primitive return type, can return implicitly convertedpublic int foo( ) char c;return c;/ char compatible with int4. For primitive return type, can explicitly castpublic int foo( ) float f = 32.5f;return (int)f;5. Must not return anything with void6. For obj. ref. return type, can return any obj. that implicitly casta. public Car getCar( ) return new BMW( );/ assume BMW extends Car (IS-A)b. public Object getObject( ) int nums = 1, 2, 3;return nums;/ still an objectc. public interface Chewable public class Gum implements Chewable public class TestChewable public Chewable getChewable( ) return new Gum( );/ return interface implementer8. Constructors and InstantiationConstructor BasicEvery class, including abstract class, MUST have a constructorNo need to type it, system will provide default constructorclass Foo Foo( ) / constructor1. Constructor have NO return type2. Name must exactly match the class nameclass Foo int size;Foo(int size) this.size = size;Foo f = new Foo( );/ ERRORFoo f = new Foo(43);/ OKConstructor Chaining4. Object3. Car( ) call super( )2. BMW( ) call super( )1. main( ) call new BMW( )Rules for Constructor1. Constructor can use any access modifier, including private2. Constructor name must match the name of class3. Constructor must NOT have a return type4. Its legal to have a method with the same name as class, but its NOT constructor5. If dont type a constructor, compiler will auto gen a default constructor6. The default constructor ALWAYS no-arg7. If theres constructor with arg, no default constructor will be created8. Every constructor, its 1st stmt either call to overloaded (this) constr. or superclass (super)9. If you type in constructor, do not type in super or this, compiler will call super( )10. super can be no-args or have arg. pass to superclass11. A no-arg constructor is not necessarily the default constructor, although the default constructor is always no-arg12. Cannot make a call to instance method or access inst. var until after a call to super13. only static var. and method can be accessed as part of the call to super( ) or this( )14. Abstract class hv constructor, when concrete subclass is instantiated15. Interface do not have constructor16. The only way a constructor be invoked is from another constructore.g. class Car Car( ) void doStuff( ) Car( );/ ERRORWhether a Default Constructor will be created1. class Horse Horse ( ) / NOHorse (String horse) 2. class Horse Horse (String horse) / NO3. class Horse / YES4. class Horse void Horse( ) / YES, NOT a constructor- if the superclass have arg. constructor, must type a constructor in subclass since need call super with appropriate arg.- constructor are never inherited, they are not metho
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- GB/T 26941-2025隔离栅
- 物业承包合同下新增厨师补充协议范文8篇
- 压力真空罐安全培训流程课件
- 2025年区块链行业区块链技术应用前景与金融改革研究报告
- 2025年物联网行业物联网技术应用前景研究报告
- 2025年火箭航天行业商业化前景预测报告
- 2025年环保行业绿色环保产品市场前景研究报告
- 2025年虚拟现实行业VR技术与虚拟现实应用前景研究报告
- 商品车电器使用培训课件
- 商品混凝土安全技术培训课件
- 股权代持协议(模板)8篇
- 《AI创意课件之设计》课件
- 医院会计笔试题目及答案
- 河南豫信电科所属公司招聘笔试题库2025
- GB/T 45345-2025金属及其他无机覆盖层工程用直流磁控溅射银镀层镀层附着力的测量
- 无人机教员聘用协议书
- 药物非临床研究质量管理规范
- 脑科生理病理图谱解读
- 全国青少年科技辅导员专业水平认证笔试考题
- (行业)常用表面处理工艺详解(行业讲座教学培训课件)
- 配电网安健环设施标准
评论
0/150
提交评论