Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA."— Presentation transcript:

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

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

3 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

4 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.

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

6 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:

7 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

8 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

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

10 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”

11 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

12 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)

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

14 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

15 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

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

17 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.}

18 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

19 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

20 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 }}

21 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); } }}

22 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

23 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

24 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

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

26 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

27 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)

28 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());}}

29 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

30 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

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

32 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.}

33 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()}

34 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

35 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

36 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(); }}

37 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

38 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

39 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 }

40 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


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

Similar presentations


Ads by Google