Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
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. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Chapter 10 Classes Continued
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Ingeniería de Sistemas ertificación en AVA.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
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.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
BY:- TOPS Technologies
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
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,
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Chapter 11 Inheritance and Polymorphism
Final and Abstract Classes
Inheritance and Polymorphism
ATS Application Programming: Java Programming
Object Oriented Programming
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Overloading and Overriding
Week 6 Object-Oriented Programming (2): Polymorphism
Java – Inheritance.
Final and Abstract Classes
Presentation transcript:

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA

6. OBJECTS AND CLASSES  Objectives  Benefits of Object-Oriented Implementation  Implementing Object-Oriented Relationships  Overloading and Overriding  Constructors and subclassing  Inner classes

Objectives State the benefits of encapsulation in OO design, and write code that implements tightly encapsulated classes and the relationship “is a” and “has a” State the legal return types for any method given the declarations of all related methods in this or parent classes Write code to invoke overriden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these methods Declare classes, inner classes, methods, instance variables, static variables, and automatic (method local) variables, making appropriate use of all permitted modifiers (such as public, final, static, abstract, adn so forth). State the significance of each of these modifiers both singly and in combination, and state the effect of package relationships on declared items qualified by these modifiers

Objectives... Write code to construct instances of any concrete class, including normal top-level classes, inner classes, static inner classes, and anonymous inner classes Identify correctly constructed source files, package declarations, import statements, class declarations (of all forms, including inner classes), interface declarations and implementations (for java.lang.Runnable or other interface described in the test), method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers.

Benefits of Object-Oriented Implementation 1.Abstract data type 2.Inheritance Encapsulation can make code more reliable and robust Inheritance: Reuse

Abstract Data types Well-encapsulated aggregate of data and behavior What matters are the operations that you can perform on these data items and the boundary conditions within which you can expect those operations to work properly State clearly the operations that can beState clearly the operations that can be applied to instances of that class How to represent the state of the instanceHow to represent the state of the instance (variables of private accessibility) Goals:

Square root : non-negative numbersSquare root : non-negative numbers Addition: each argument should be at mostAddition: each argument should be at most half the maximum representable for its return type Boundary condition limit on the range of arguments for which a method can operate properly All behavior should be accessed only via methods. Thus, you can change the nature of storage freely You may add new methods to provide additional functionality freely

Reuse 1.Using composition: “has a” relationship 2.Using inheritance: “is a” relationship If a class is well encapsulated, it will be easier to reuse successfully The more a class is reused, the better tested it will be and the fewer bugs it will have

Implementing OO relationships Here, implementation of classes for which a basic description has been given “is a”: superclasses “has a”: member variable

1.public class Home extends House { 2.Family inhabitants; 3. Pet thePet; 4.} “A home is a house that has a family and a pet”

Overloading and overriding Reusing the same name for a method Overloading: Reusing the same method name with different arguments and perhaps a different return type Overriding: Using the same method name with identical arguments and return type

Conditions to reuse a method name 1.In an unrelated class, no special conditions apply and the two methods are not considered related in any way 2. In the class that defines the original method, or a subclass of that class, the method name can be reused if the argument list differs in terms of the type of at least one argument (overloading) 3. In a strict subclass of the class that defines the original method, the method name can be reused with identical argument types and order and with identical identical argument types and order and with identical return type (overriding)

A difference in return type alone is not sufficient to constitute an overload and is illegal !!! Strict subclass: A subclass excluding the class itself

1.public void aMethod(String s){ } 2.public void aMethod(){ } 3.public void aMethod(int i, String s){ } 4.public void aMethod(String s, int i){ } Overloading method names A method is uniquely identified by the combination of its fully qualified class name, method name, and the exact sequence of its argument types public void aMethod(int j, String name) { } Only the argument types are considered not their names Same as the one in line 3 above

What is overloading for? Area of a triangle Input: 1.Cartesian coordinates 2.Polar coordinates 3.Lengths of the three sides creating several methods that perform closely related functions under different conditions Use overloaded method names in situations where the methods really perform the same basic function with different data sets

Overloaded methods can have different return types types addition int addUp(int, int) float addUp(float, float) double addUp(double, double)

Invoking overloaded methods The compiler decides which method to call simply by looking at the argument list and that the various overloaded methods are in fact unrelated 1.public class RightJustify { 2.private static final String padding= 3. “ “ + 4. “ “ ; // 80 spaces 5.public static void print( String s, int w ) { 6. System.out.print(padding.substring(0, s.length()-w)); 7. System.out.print(s); 8.} 9. public static void print( int i, int w ) { 10. print( “ ”+ i, w) 11. } 12.}

About overloading methods (summary)  The identity of a method is determined by the combination of its fully qualified class, name, and the type, order, and count of arguments in the argument list  Two or more methods in the same class (including methods inherited from a superclass with the same name but different argument lists are called overloaded  Methods with overloaded names are effectively independent methods- using the same name is really just a convenience to the programmer. Return type, accessibility, and exception lists may very freely  Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list

Method overriding Used when you need to modify the behavior of a method of a superclas to suit your new class Overloaded methods Overriden methods Suplement each other Replace themethods they override Can exist, in any number, in the same class Each method in a parent clas can be overriden at most once in any one subclass Must have different argument lists Must have argument lists of identical type and order The return type may be chosen freely Must be identical to that of the method it overrides

class Rectangle { int x,y,w, h; public void setsize (int w, int h) { this.w = w; this.h = h; this.w = w; this.h = h; } } class DisplayedRectangle extends Rectangle { public void setsize (int w, int h) { this.w = w; this.w = w; this. h = h; this. h = h; redisplay(); // implementation redisplay(); // implementation } public void redisplay() { public void redisplay() { // implementation not shown // implementation not shown }}

public class TestRectangle { public static void main (String[] args) { public static void main (String[] args) { Rectangle[] recs = new Rectangle[4]; Rectangle[] recs = new Rectangle[4]; recs[0] = new Rectangle(); recs[0] = new Rectangle(); recs[1] = new DisplayedRectangle(); recs[1] = new DisplayedRectangle(); recs[2] = new DisplayedRectangle(); recs[2] = new DisplayedRectangle(); recs[3] = new Rectangle(); recs[3] = new Rectangle(); for (int i=0; i < recs.length; i++) { for (int i=0; i < recs.length; i++) { int w= ((int)(Math.random()*400)); int w= ((int)(Math.random()*400)); int h= ((int)(Math.random()*200)); int h= ((int)(Math.random()*200)); recs[i].setSize(w, h); recs[i].setSize(w, h); } }}

About overriding methods (summary)  The method name and the type and order of arguments must be identical to those of a method in a parent class.  The return type must be identical  The accesibility must not be more restricted than the original method  The method must not throw checked exceptions of classes that are not possible for the original method

Late binding or virtual method invocation When a compiler in a non-OO language comes across a method invocation, it determines exactly what target code should be called and builds machine language to represent that call. In an OO language, instead, code will be generated that will allow the decision to be made at runtime (late binding or virtual method invocation) binding: the job a linker does when it glues various bits of machine code together to make an executable program file

1.class Rectangle { 2.private int x, y, w, h; 3.public String toString() { 4. return “x= “+ x + “, y= “+ y + 5. “, w= “+ w + “, h “+ h; 6. } 7.} 7.} 8.class DecoratedRectangle extends Rectangle { 9.private int borderWidth; 10.public String toString() { 11. return super.toString() + “, borderWith = “+ 12. borderWidth; 13. } 14.} Invoking overriden methods Invoking an overriden method from the method it overrides

Invokes the method that is “next up the tree” super.xxx() You cannot bypass a level in the hierarchy!!

Key points about overriding methods  A method which has an identical name, and identical number, types and order of arguments as a method in a parent class is an overriding method  Each parent class method may be overrriden at most once in any one subclass  Overriding methods must returnexactly the same type as the method they override  An overriding method must not be less accessible than the method it overrides

Key points about overriding methods...  An overriding method must not throw any checked exceptions that are not declared for the overriden method  An overriden method is completely replaced by the overriding method unless the overriden method is deliberately invoked from within the subclass  An overriden method can be invoked from within the subclass using using the construction super.xxx(), where xxx() is the method name. Methods that are overriden more than once (by chains of subclasses)

Overloading constructors public class AnyClass { public AnyClass (int a, String b, float c, Date d) { // Complex processing to initialize based on arguments // Complex processing to initialize based on arguments} public AnyClass( int a) { this (a,“default”,0.0F, new Date()); this (a,“default”,0.0F, new Date());}}

About overloading constructors (summary)  You can only create an object if a constructor with an argument list that matches the one your new call provides is defined in the class itself  If you define no constructors at all in a class, then the compiler provides a default that takes no arguments. If you define even a single constructor, this default is not provided  one constructor can call an overloaded constructor using the syntax this(arguments...)  A constructor delays running its body untile the parent parts of the class have been initialized  A constructor can use overloaded constructor versions to support its work. These are invoked using the syntax this(arguments...) and if suppiled, this call must be tghe first statement of the constructor

Inner classes public class OuterOne { private int x; public class InnerOne { private int y; public void innerMethod() { System out println(“y is ” + y); }} public void outerMethod() { System. out. println(“x is ”+x); } // other methods } The same as any other class, but is declared inside

OuterOneOuterOne.InnerOne Objects that are instances of the inner classes generally retain the ability to access the member of the outer class Two classes

The Enclosing this reference and Construction of inner classes 1.public class OuterOne { 2.private int x; 3.public class InnerOne { 4.private int y; 5.public void innerMethod() { 6. System out println(“enclosing x is ” + x); 7. System out println(“y is ” + y); 8. } 9.} 10.public void outerMethod() { 11.System. out. println(“x is ”+x); 12.} 13.public void makeInner() { 14.InnerOne anInner = new InnerOne(); 15. anInner. innerMethod(); 16.} 17.// other methods 18.}

The accesibility of the members of the enclosing class is possible because the inner class has a hidden reference to the outer class instance that was the current context when the inner class object was created public static void main() { OuterOne.InnerOne i = new OuterOne().new InnerOne(); i.innerMethod();} public static void main() { OuterOne o = new OuterOne(); OuterOne.innerOne i = o.new InnerOne(); OuterOne.innerOne i = o.new InnerOne();i.innerMethod()}

Static inner classes  A static inner class does not have any reference to an enclosing instance  Methods of a static inner class cannot access instance variables of the enclosing class. But they can access static variables of the enclosing class  You can create an instance of a static inner class without the need for a current instance of the enclosing class Not only can you declare a class inside another class, but you can also declare a class inside a method of another class

Classes defined inside methods 1.An object created from an inner class within a method can have some access to the variables of the enclosing method 2.It is possible to create an anonymous class, a class with no specified name

public class MOuter { public static void main(String args [] ) { Mouter that=new Mouter(); that.go((int)(Math.random()*100),(int)(Math.random()*100));} public void go(int x, final int y) { int a=x+y; final int b=x-y; class Minner { public void method() { public void method() { // System out println(“x is ” + x); // Illegal ! System out println(“y is ” + y); System out println(“y is ” + y); // System out println(“a is ” + a); // Illegal ! System out println(“b is ” + b); System out println(“b is ” + b); } }} Minner that= new Minner(); that.innerMethod(); }}

Anonymous classes public void aMethod() { theButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) { System.out.println(“The action has occurred”); } });} Classes inside a method that do not need a name  They are defined in the place they are constructed  They should be small

About anonymous classes (key points)  The class is instantiated and declared in the same place  The declaration and instantiation takes the form new Xxxx () { // body } Xxxx is an interface name  An anonymous class cannot have a constructor

Aditional features of anonymous inner classes An anonymous class can be a subclass of another explicit class, or it can implement a single explicit interface. It cannot be both an explicit subclass and implement an interface (extending Object is implicit where an interface is implemented) If an anonymous class extends an existing class, rather than implementing an interface, then arguments for the supperclass constructor may be placed in the argument part of the new expression new Button( “Press Me”) { // define some modification of Button }

For anonymous classes that implement interfaces, the parent class is java.lang.Object It is impossible to use any arguments in the new part for these classes