peyman dodangeh sharif university of technology fall 2014

62
Advanced Programming in Java Peyman Dodangeh Sharif University of Technology Fall 2014

Upload: janel-lamb

Post on 05-Jan-2016

218 views

Category:

Documents


3 download

TRANSCRIPT

Advanced Programming in Java

Advanced Programming in JavaPeyman DodangehSharif University of TechnologyFall 2014AgendaInheritanceClass Hierarchiesis-a relationshipUML Class Diagramprotected membersAbstract Methodssuper keywordInitialization in inheritance

Fall 2014Sharif University of Technology2Introduction to Inheritance

Class HierarchiesFall 2014Sharif University of Technology4

Class Hierarchies (2)Fall 2014Sharif University of Technology5

Class Hierarchies (3)Fall 2014Sharif University of Technology6

General and Specific TypesFaculty and Employee are both classesFaculty is a more specific type of EmployeeEmployee is a more general type of Faculty A Faculty instance is also a Employee instanceDr. Felani is a faculty memberHe is also an employee of university

Fall 2014Sharif University of Technology7is-a RelationshipMore general class : SuperclassMore specific class : SubclassSubclass is inherited from superclass

Faculty is inherited from EmployeeRectangle is inherited from ShapeA rectangle is also a shapeCat is inherited from AnimalMaloos is a cat, she is also an animal

Fall 2014Sharif University of Technology8Inheritance (2)Name some other hierarchiesNote: More specific type is also a classNot an objectAli Karimi is not a more specific type of FootballPlayerHe is an objectNot a class

Fall 2014Sharif University of Technology9Class ImplementationHow do you implement Employee class?How do you implement Faculty class?Fall 2014Sharif University of Technology10Fall 2014Sharif University of Technology11

Fall 2014Sharif University of Technology12Inheritance in OOPJava offers inheritancelike any object oriented programming languageInheritance is used for implementing more specific classesDuplicate code is eliminatedInheritance provides code reuseis-a relationship

Fall 2014Sharif University of Technology13

Faculty & EmployeeFaculty is inherited from EmployeeFaculty extends EmployeeAttributes and behaviors of Employee is inherited to FacultyInheritance provides code reuse

Fall 2014Sharif University of Technology14UML Class DiagramFall 2014Sharif University of Technology15

UML Class DiagramFall 2014Sharif University of Technology16

class Shape{int color;int positionX, positionY;}class Circle extends Shape{private int radius;public double getArea(){return 3.14*radius*radius;}}class Rectangle extends Shape{private int width, length;public double getArea(){return width*length;}}

Fall 2014Sharif University of Technology17TerminologyClass Rectangle is inherited from class Shape

Rectangle is a subclass of ShapeRectangle is a child of ShapeRectangle is a derived class of Shape

Shape is the super-class of RectangleShape is the parent of RectangleShape is the base-class of Rectangle

Rectangle is-a Shape

Fall 2014Sharif University of Technology18Inheritance in javaEvery class is inherited from class ObjectPrimitive-types are not objectsObject class has some operationsequals()toString()Every class adds some operationsAnd may changes some operationstoString()

Fall 2014Sharif University of Technology19InheritanceSoftware reusabilityCreate new class from existing classAbsorb existing classs data and behaviorsEnhance with new capabilitiesSubclass extends superclass. Subclass:More specialized group of objectsBehaviors inherited from superclassOr changed and customizedAdditional behaviorsFall 2014Sharif University of Technology20Class HierarchyDirect superclassInherited explicitly (one level up hierarchy)Indirect superclassInherited two or more levels up hierarchySingle inheritanceInherits from one superclassMultiple inheritanceInherits from multiple superclassesJava does not support multiple inheritance

Fall 2014Sharif University of Technology21is-a relationshipObject of subclass is a object of super-classExample: Rectangle is quadrilateral.Class Rectangle inherits from class QuadrilateralQuadrilateral: superclassRectangle: subclassSuperclass typically represents larger set of objects than subclassessuperclass: Vehiclesubclass: CarSmaller, more-specific subset of vehicles

Fall 2014Sharif University of Technology22More ExamplesFall 2014Sharif University of Technology23

Subclasses mayAdd new functionalityNew membersUse inherited functionalitySoftware reuseOverride inherited functionalityChange parent methods

Fall 2014Sharif University of Technology24Software reuseSoftware reuse is at the heart of inheritanceUsing existing software components to create new onesCapitalize on all the effort that went into the design, implementation, and testing of the existing software

Fall 2014Sharif University of Technology25Bad smellAvoid Copy & Paste!Avoid Copy & Paste!Avoid Copy & Paste!Avoid Copy & Paste!Avoid Copy & Paste!Avoid Copy & Paste!Avoid Copy & Paste!Please, Avoid Copy & Paste!

Fall 2014Sharif University of Technology26public class Person {private String name;private Long nationalID;public String getName() {return name;}public void setName(String name) {this.name = name;}public Long getNationalID() {return nationalID;}public void setNationalID(Long nationalID) {this.nationalID = nationalID;}public void show() {System.out.println("Person: name=" + name + ",nationalID=" + nationalID);}}Fall 2014Sharif University of Technology27class Student extends Person{private String studentID;public void setStudentID(String studentID) {this.studentID = studentID;}public String getStudentID() {return studentID;}public void takeCourse(Course course){...}public void show(){System.out.println("Student: name=" + getName() + ",nationalID=" + getNationalID()+ ",studentID=" + studentID);}}Fall 2014Sharif University of Technology28New propertiesNew methods (more behavior)Change parent methods(Override)Use parent methods(Software Reuse)28Person p1 = new Person();p1.setName("Ali Alavi");p1.setNationalID(1498670972L);p1.show();

Student st = new Student();st.setName("Ali Alavi");st.setNationalID(1498670972L);st.setStudentID("89072456");st.show();

Fall 2014Sharif University of Technology29Defined in ParentAdded in ChildChanged in ChildQuiz!Fall 2014Sharif University of Technology30

What type of inheritance does Java have? (Single, Double, Multiple, )

Draw a UML class diagram for these classes: Movie, HorrorMovie, and ComedyMovie.

Can an object be a subclass of another object?

Does a subclass inherit both member variables and methods?

Mammal is a subclass of Animal. Because of single inheritance...Mammal has no subclasses.Mammal has no parent other than Animal.Animal has only one subclass.Mammal has no siblings.

Fall 2014Sharif University of Technology31More About InheritanceRemember Animals Class HierarchyFall 2014Sharif University of Technology33

Abstract BehaviorsDoes any animal swim?No. So to swim is not a behavior of animals.Any animal has a voiceto talk is a behavior of animalsBut what is the voice of an animal?How does an animal talk?It depends to the specific type of animalDog: Hop! Hop!Cat: Mewww!

Fall 2014Sharif University of Technology34Abstract Behaviors (2)talk is an abstract behavior of AnimalAll animals can talkBut we can not specify how an animal talksIt depends to the specific class of animaltalk is a concrete behavior of DogHop! Hop!swim is not a behavior of AnimalAll animals can not swimswim is a concrete behavior of Fish

Fall 2014Sharif University of Technology35Remember Shape ClassesFall 2014Sharif University of Technology36

Fall 2014Sharif University of Technology37

Fall 2014Sharif University of Technology38

Fall 2014Sharif University of Technology39

Shapes ExampleShape is an abstract classSome methods are undefined in ShapeSome methods should be defined in sub-classesgetArea()getPerimeter()These methods are abstract methodsRemember abstract behaviorsFall 2014Sharif University of Technology40Abstract MethodsShape classesgetArea()draw()Animals Talk()getName() is not abstract!How do you implement an abstract method?We can implement these methods by simple dummy operationsBetter way : abstract methodsFall 2014Sharif University of Technology41Abstract Methods (2)abstract method : no implementationA class containing abstract methods: an abstract classYou can not instantiate abstract classesWhy?If a sub-class do not implement the abstract methodIt will be abstract tooFall 2014Sharif University of Technology42Animal ExampleFall 2014Sharif University of Technology43

Animal Example (2)Fall 2014Sharif University of Technology44

Access modifier in inheritanceYou can not override a public method as a private methodWhy?It violates the is-a ruleYou can not reduce accessibility of methods in subclasses

Fall 2014Sharif University of Technology45Accessibility of MembersSubclass has access to public members of parent classPublic methods and properties are accessible in subclassStudent used getName() and getStudentID()Private members are not accessible in subclassStudent has no access to name and studentID propertiesWhat if you want to let subclasses access a member, but not other classes?

Fall 2014Sharif University of Technology46Protected MembersIntermediate level of protection between public and privateprotected members accessible bysubclass membersClass members in the same packageprotected members are also package accessiblefriendlyProtected variables and methods are shown with a # symbol in UML diagrams

Fall 2014Sharif University of Technology47UML Class DiagramFall 2014Sharif University of Technology48

Access LevelsPublicAccessible by all classesProtectedAccessible by subclassesAccessible by classes of the same packagePackage access (friendly)Accessible by classes of the same packagePrivateNo access

Fall 2014Sharif University of Technology49super KeywordAccess to parent membersThe super reference can be used to refer to the parent classsuper.f() invokes f() from parent classWhy we need it?When the method is overridden in subclasssuper is also used to invoke the parent's constructor

Fall 2014Sharif University of Technology50Application of super Keywordclass Student extends Person{public void show(){super.show();System.out.println(",studentID=" + studentID);}}

Fall 2014Sharif University of Technology51Variable ScopesFall 2014Sharif University of Technology52

Object class methodsequals()toString()finalize()

We can override these methods in our classesFall 2014Sharif University of Technology53Multiple InheritanceJava supports single inheritanceDerived class can have only one parent classMultiple inheritance allows a class to be derived from two or more classesinheriting the members of all parentsCollisions, such as the same variable name in two parents, have to be resolvedJava does not support multiple inheritanceThe use of interfaces usually gives us aspects of multiple inheritance without the overhead

Fall 2014Sharif University of Technology54InitializationConstructors are not inheritedeven though they have public visibilityWe often want to use the parent's constructor to set up the "parent's part" of the objectFall 2014Sharif University of Technology55

ConstructorsA childs constructor is responsible for calling the parents constructorIt is done using super keywordThe first statement of a childs constructor should be the super reference to call the parent constructorOtherwise, default constructor is implicitly invokedIf default constructor does not exist? (how?!)A syntax errorYou should explicitly call an appropriate parent constructorFall 2014Sharif University of Technology56class Person {private String name;private Long nationalID;public Person(String name, Long nationalID) {this.name = name;this.nationalID = nationalID;}}

class Student extends Person{private String studentID;public Student(String name, Long naID, String stID) {super(name, naID);this.studentID = stID;}}

Person p1 = new Person("Ali Alavi", 1498670972L);Student st = new Student("Ali Alavi", 1498670972L, "89072456");

Fall 2014Sharif University of Technology57Order of initializationOnce per classStatic variable declaration of parentStatic block of parentStatic variable declarationStatic blockOnce per objectvariable declaration of parentInitialization block of parentConstructor of parentvariable declarationInitialization blockConstructor

Fall 2014Sharif University of Technology58public class Parent {static int a = A();static{a=B();}int b = E();{b = F();}public Parent(){b = G();}}Fall 2014Sharif University of Technology59class Child extends Parent{static int c = C();static{c=D();}int b = H();{b = I();}public Child(){b = J();}}

What happens if we invoke: new Child();Some NotesAs the first statement of a constructor, we can invoke parent constructorUsing super keywordOnly onceFirst line? No. first statement.We can not use properties in this super invocationsuper(this.name)Why?

Fall 2014Sharif University of Technology60ExerciseDesign these classes and draw a UML class diagram for:ObjectPerson (name, phoneNumber)Student (average, entranceYear)MS Student (thesis title)Instructor (offeredCourses)

Fall 2014Sharif University of Technology61Fall 2014Sharif University of Technology62

SuperclassSubclasses

StudentGraduateStudent, UndergraduateStudent

ShapeCircle, Triangle, Rectangle

LoanCarLoan, HomeImprovementLoan, MortgageLoan

EmployeeFaculty, Staff

BankAccountCheckingAccount, SavingsAccount