1 / 53

Application development with Java

Application development with Java. Lecture 21. Inheritance. Inheritance Subclasses Overriding Object class. Inheritance Idea. Creation of new software from existing software components by adding only. You create objects of your class inside a new class. This is called composition .

bgilfillan
Download Presentation

Application development with Java

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. Application development with Java Lecture 21

  2. Inheritance • Inheritance • Subclasses • Overriding • Object class

  3. Inheritance Idea • Creation of new software from existing software components by adding only. • You create objects of your class inside a new class. • This is called composition. • New class composed of objects of existing classes.

  4. Superclass and Subclass • Inheritance allows us to derive new classes from existing ones. • The existing class is called superclass. • The class that does the inheriting is said to be a subclass of the class from which it inherits. • Sometimes the terms derived class and base class are used instead of subclass and superclass.

  5. Inheritance • Instances of the derived class inherits all the properties and functionality that are defined in base class. • A derived class can add to the state and behavior that it inherits. • It can also replace or modify inherited behavior.

  6. Example Some examples of superclasses and subclasses:

  7. Rules of Thumb • Inheritance creates is-a relation. • if x is-a y - than x could extend y • ColoredPoint is a Point. • Everything that can be done with a Point object can be done with ColoredPoint object. • ColoredPoint has all the functionality of a Point and some more.

  8. Example

  9. Another example Student - is a person who studies in the university or college. CS Student - is a person who studies computer science in the university or college. CS female Student – is a person who studies computer science in the university or college and it’s gender is female.

  10. Another example • Student is a superclass of CS Student is a superclass CS female Student is a superclass CS female student in IDC. • CS female student in IDC is a subclass of CS female Student is a subclass of CS Student is a subclass of Student.

  11. Creating a subclass • A keyword extends used to show that the current class is a subclass of other class. • Usually we try to extend the superclass data and methods by adding new features. Syntax: class class_name extends super_class_name { // additions to, and modifications of stuff inherited // from super class }

  12. Example /** * A ColoredPoint class represents a Point object * with new data field color. */ public class ColoredPoint extends Point { private Color color; // …  }

  13. Example • Subclass can also have new methods. public class ColoredPoint extends Point { private Color color;  // new method void setColor(Color color) { this.color = color; } }

  14. Subclass • When you derive a class from a given base class: • The subclass inherits all the fields of the base class • It inherits all the methods of the base class • Private fields and methods in the base class are inherited but they cannot be accessed directly from the code of the subclass. • They are private and encapsulated in the base class itself.

  15. Subclass methods • Subclass can do one of the following with each inherited method: • use the method as it is • change it’s implementation – override • Subclass can also have methods and data of his own, i.e. add methods.

  16. Example

  17. Constructors • Constructors are not inherited. • Constructors must be redefined. • We often want to use the parent's constructor to set up the "parent's part" of the object. • We do this by using the superkeyword.

  18. Example public class ColoredPoint extends Point { … // constructor public ColoredPoint(int x, int y,Color color) { super(x,y); this.color=color; } } Constructor of the Point class

  19. The super keyword • The keyword super allows to refer to the parent (super) class. • The super keyword can be used to access the method from the subclass. • The first line of the constructor must invoke one of superclass constructors using super(..). • If you do not call super(..) in the first line of the constructor the compiler automatically invoke the empty constructor of the superclass.

  20. The default constructor • The default constructor is empty constructor. • If a given class does not have a constructor a default constructor is used by the compiler. • If a subclass does not have a constructor then an empty constructor of superclass is invoked and an empty constructor of subclass itself.

  21. Super(..) • A subclass constructor needs to indicate which parent constructor to connect to. Example: super(x,y); // uses two integer constructor of Point super(); // uses default constructor

  22. Super(..) and methods • The major use of super is to override a method with a new method that extends the behavior of the inherited method. • The new method can use super to call the inherited method, and it can include additional code to provide additional behavior. • Syntax: super.method();

  23. The super keyword public class ColoredPoint extends Point { … // ColoredPoint constructor s public ColoredPoint(int x, int y,Color color) { super(x,y); // constructor of the Point class this.color=color; // additional information } public ColoredPoint(int x, int y) { super(x,y); // constructor of the Point class } … }

  24. Overriding • Overriding means changing the implementation of the method while keeping it’s signature. • Subclass can override a method implementation to provide a different version than parent. • Subclass can add some information to parent version of the method. • Subclass can completely re-define the parent’s method.

  25. Overriding • Example: We want clients to be able to open a protected file only if it is unlocked • File(String name) • isOpen() • open() • close() • getName() File • RestrictedFile(String name, long key) • isLocked() • lock() • unlock(long key) RestrictedFile

  26. File Example /** * Part of a File implementation */ public class File { // The name of the file private String name; // true if the file is opened private boolean isOpen; /** * Construct a file with a given name. */ public File(String name) { this.name = name; }

  27. File Example /** * Returns the name of the file. */ public String getName() { return name; } /** * Checks if the file is open. * @return true iff the file is open */ public boolean isOpen() { return isOpen; } // other methods/variables... }

  28. File Example /** * Opens the file. */ public void open() { // … other operations isOpen = true; } /** * Closes the file. */ public void close() { // … other operations isOpen = false; } }

  29. RestrictedFile Example /** * Represents a restricted file, which can be * opened only if it is unlocked. In order to * unlock the file a key is needed. */ public class RestrictedFile extends File { // Password for unlocking the file private long key; // The state of the file - locked/unlocked private boolean isLocked;

  30. RestrictedFile Cont. // Constructs a new restricted file. // The key is used to unlock the file public RestrictedFile (String name, long key) { super(name); this.key = key; isLocked = true; } //Checks if the file is locked. public boolean isLocked() { return isLocked; }

  31. RestrictedFile Cont. // Locks the file. public void lock() { isLocked = true; } // Unlock the file. // The file will be unlocked only // if the given key matches. public void unlock(long key) { if (this.key == key) { isLocked = false; } }

  32. RestrictedFile Cont. // Unlock the file. // The file will be unlocked only // if the given key matches. public void unlock(long key) { if (this.key == key) { isLocked = false; } }

  33. Locking? • So far the implementation is useless if we do not change the implementation of open()!

  34. RestrictedFile Overrides // Open the file. The file will be // opened only if it is unlocked. public void open() { if (!isLocked()) { super.open(); } }

  35. Overriding in RestrictedFile • RestrictedFile inherits the interface of File, but changes the functionality of the method open(). • We say that RestrictedFile overrides the method open(). • Notice the call to super.open() - we invoke the method open() of the superclass on this object. (what if we just write “open()”?)

  36. Rules of Overriding • When you derive a class B from a class A, the interface of class B will be a superset of that of class A (except for constructors). • You cannot remove a method from the interface by subclassing (why?). • However, class B can override some of the methods that it inherits and thus change their functionality. • The contract of a method states what is expected from an overriding implementation of the method.

  37. Visibility modifiers • Visibility modifiers determine which class members get inherited and which do not, which members are accessible and which are not. • Any member (variable,method and constructor) can be declared with one of the 4 visibility modifiers: • public • private • protected

  38. Visibility modifiers (revisited) • public – accessible anywhere, inherited by all subclasses of its class. • private – only code of the same class in which the member has been defined can access this member, inherited by subclasses of its class but can not be accessed directly from the code of the subclass. • protected – accessible by any class in the same package as its class, inherited by all subclasses of its class. • default – accessible by any class in the same package as its class, inherited by any class in the same package.

  39. The final Modifier • The final modifier can be used for classes, methods and variables, in each case it has a different meaning. • A final variable can be initialized only once (constants). • A final class can not have derived classes. • A final method cannot be overridden.

  40. Inheritance • Several classes can be declared as subclasses of the same superclass. • These subclasses share some structures and behaviors - the ones they inherit from their common superclass. • The superclass expresses these shared structures and behaviors. • Inheritance can also extend over several "generations" of classes.

  41. Inheritance is Transitive • In the diagram class E is a subclass of class D which is itself a subclass of class A. In this case, class E is considered to be a subclass of class A, even though it is not a direct subclass.

  42. The Object Class • Java defines the class java.lang.Object that is defined as a superclass for all classes. • All classes directly or indirectly extend the Object class. • If a class does not specify explicitly which class it is derived from, then it will be implicitly derived from class Object. • All classes inherit Object’s methods.

  43. Hierarchy Diagram Object • We can depict the relationship between this classes in the following diagram, that is called class hierarchy diagram. Point ColoredPoint

  44. Class Hierarchy Diagram: A Tree! Object Turtle IOval File IPoint RestrictedFile

  45. All Classes Extend Object • The following two class definitions are equivalent: • class SomeClass • { • // some code • } • class SomeClass extends Object • { • // some code • }

  46. Methods of Object Class • The Object class defines a set of methods that are inherited by all classes. • Some of them are: equals(Object o), getClass(), toString() • toString() method that is used whenever we want to get a String representation of an object. • When you define a new class, you can override the toString() method in order to have a suitable representation of the new type of objects as Strings.

  47. toString() Method • The toString() method is used whenever we want to get a String representation of an object. • When you define a new class, you can override the toString() method in order to have a suitable representation of the new type of objects as Strings.

  48. equals() Method • The equals()method receives an Object as a parameter. Since all classes are derived from Object, every class “is an” Object. • The implementation just checks if the two references (this and obj) are the same. • You can override this method in order to fit your class logic (when are two points equal?, when are two URLs equal?)

  49. Overloading Vs. Overriding • Overloading deals with multiple methods in the same class with the same name but different signatures. • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature. • Overloading lets you define a similar operation in different ways for different data. • Overriding lets you define a similar operation in different ways for different object types.

  50. Overriding toString() public class Point { private int x,y; public Point(int x, int y) { this.x=x; this.y=y; } public int getx() {return x;} public int gety() {return y;} public String toString() { return "(" + x + "," + y + ")"; } }

More Related