1 / 191

March, 23 - 24, 2013 SWU, Blagoevgrad

Lesson 3 Java and O-O Programming /Methods, Classes, Inheritance, Polymorphism, Interfaces/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev. March, 23 - 24, 2013 SWU, Blagoevgrad. Lesson Contents:. Structured Programming – theory & practice OOP – theory & practice

Download Presentation

March, 23 - 24, 2013 SWU, Blagoevgrad

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. Lesson 3Java and O-O Programming/Methods, Classes, Inheritance, Polymorphism, Interfaces/AUBG ICoSCIS TeamAssoc. Prof. Stoyan Bonev March, 23 - 24, 2013 SWU, Blagoevgrad

  2. Lesson Contents: • Structured Programming – theory & practice • OOP – theory & practice • Java methods • Java classes • Inheritance • Polymorphism • Abstract classes and Interfaces

  3. Structured Programming – theory • Structured programming: A technique for organizing and coding computer programs in which a hierarchy of modules is used, each having a single entry point and a single exit point, and in which control is passed downward through the structure without unconditional branches to higher levels of the structure. • Dividing a program into functions and modules . • Thinking in Functions! • Basic building construct – member function or method

  4. OOP – theory • Data Encapsulation & Data Hiding: Data and its functions are said to be encapsulated into a single entity • Inheritance: The process of creating new classes or derived classes from existing classes or base classes. Inheritance as “is a kind of” relation btw classes. • Polymorphism: Ability to redefine methods for derived classes. Giving different meaning to the same thing. • Dividing a program into classes and objects . • Thinking in Classes! • Basic building construct – classes and objects

  5. StrProg – problem to solve • To develop – arithmetic operators processor • A routine for each arithmetic operator is must • Addition: int add(int p1, int p2) { return p1+p2;} • Expand it with routines for all arithmetic operators: +, -, *, /, %, ^ • Solution looks like this: public class StructProgArithCalc { public int add(int pa, int pb) { return pa + pb; } public static void main(String[] args) { System.out.println(" " + add(55, 66)); } }

  6. OOP – problem to solve • To develop – arithmetic operators processor • A separate individual class with methods for each arithmetic operator is must • Java, file OOPArithCalc.java package ooparithcalcjava; class ArithCalc { public int add(int pa, int pb) { return pa + pb; } } public class OOPArithCalc { public static void main(String[] args) { ArithCalc myCalc = new ArithCalc(); System.out.println(" " + myCalc.add(55, 66)); } }

  7. OOP – problem to solve • Build your own arithmetic operators processor. • Expand it with methods for all arithmetic operators: +, -, *, /, %, ^ • Name file as OOPArithCalc.java

  8. More on Java syntax • Methods or member functions • Predefined and User defined methods

  9. Predefined Methods Methods already written and provided by JRE Organized as a collection of classes (class libraries) To use: import <package>; Illustration: Math class, String class Java Programming: From Problem Analysis to Program Design, 4e 9

  10. Predefined methods

  11. Predefined Classes (continued) Java Programming: From Problem Analysis to Program Design, 4e 11

  12. Predefined Classes (continued) Java Programming: From Problem Analysis to Program Design, 4e 12

  13. Predefined Classes (continued) Java Programming: From Problem Analysis to Program Design, 4e 13

  14. Some Commonly Used String Methods Java Programming: From Problem Analysis to Program Design, 4e 14

  15. Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 15

  16. Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 16

  17. Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 17

  18. Some Commonly Used String Methods (continued) Java Programming: From Problem Analysis to Program Design, 4e 18

  19. User-Defined Methods User-defined methods in Java are classified in two categories: Value-returning methods Methods have a return data type Methods return a value of specific data type using return statement Used in expressions, Calculate and return a value Can save value for later calculation or print value Void methods Methods that do not have a return data type Methods do not use return statement to return a value Java Programming: From Problem Analysis to Program Design, 4e 19

  20. Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. int sum = 0; for (inti = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (inti = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (inti = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum);

  21. Solution public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i <= i2; i++) sum += i; return sum; } public static void main(String[] args) { System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); }

  22. Creating/Defining Methods A method is a collection of statements that are grouped together to perform an operation.

  23. Calling Methods • In creating a method, you give a definition of what the method is expected to do. • To use a method, you have to call it, or invoke it, or activate it in two ways depending on the method category: • As a value, (i.e. operand of an expression) • Larger = max(20, 50); • System.out.println(“Result is=“, max(20,50)); • As a statement • System.out.println(“JAVA”);

  24. Calling Methods, cont.

  25. void method example This type of method does not return a value. The method performs some actions. public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } Suppose you invoke the method using • nPrintln(“Welcome to Java”, 5); What is the output? Suppose you invoke the method using • nPrintln(“Computer Science”, 15); What is the output?

  26. Passing parameters by Values When calling a method, the argument value is passed /copied/ to the formal parameter. The argument is not affected, regardless of the changes made to the parameter inside the method.

  27. Overloading Methods Overloading the max Method public static double max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, double num2){ if (num1 > num2) return num1; else return num2; }

  28. Arrays and Methods • Passing Arrays to methods • Through parameter passing mechanism by value • Returning an Array from a Method • Through return stmt

  29. Arrays and Methods public static int[] arrayProcess(int[] par) { int j; int[] b = new int[par.length]; for (j=1; j<par.length; j++) b[j] = par[j] *10; return b; } Do you have any critical remark on the source text?

  30. Arrays and Methods public static void main(String[] args) { int[] ar = new int[10]; for (i=0; i < ar.length; i++) ar[i] = i; int[] br; br = arrayProcess(ar); for (i=0; i < br.length; i++) System.out.print(br[i] + " "); } // end of main

  31. Pass By Value Java uses pass by value to pass arguments to a method. There are important differences between passing a value of variables of primitive data types and passing arrays. For a parameter of a primitive type value, the actual value is passed. Changing the value of the local parameter inside the method does not affect the value of the variable outside the method. For a parameter of an array type, the value of the parameter contains a reference to an array; this reference is passed to the method. Any changes to the array that occur inside the method body will affect the original array that was passed as the argument. 31 11/5/2014 Assoc. Prof. Stoyan Bonev

  32. public class Test { public static void main(String[] args) { int x = 1; // x represents an int value int[] y = new int[10]; // y is an array of int values m(x, y); // Invoke m with arguments x and y System.out.println("x is " + x); System.out.println("y[0] is " + y[0]); } // end of main public static void m(int number, int[] numbers) { number = 1001; // Assign a new value to number numbers[0] = 5555; //Assign new value to numbers[0] } // end of m } // end of class Test Simple Example 32 11/5/2014 Assoc. Prof. Stoyan Bonev

  33. Exercise on methods • Expand the program Methods1.java adding more methods that reside in the same class with method main(): • Iterative GCD – gcdi() • Iterative/Recursive factorial – facti(), factr() • Iterative/Recursive Fibonacci – fiboi(), fibor() • Iterative/Recursive Sum(1..n) – sumi(), sumr() • Iterative/Recursive Power operator simulator – powi(), powr() • Write a program to demonstrate the effect of passing by value. (method swap)

  34. Exercises • Palindrome: string that reads the same forwards and backwards • Write a value-returning method isPalindrome(), that returns true if a given string is palindrome, i.e. it reads the same way forwards and backwards. • The method isPalindrome() takes a string as a parameter and returns trueif the string is a palindrome, false otherwise • Write a Java program to test the method

  35. Solution: isPalindrome() Method public static boolean isPalindrome(String str){ int len = str.length(); int i, j = len - 1; for (i = 0; i <= (len - 1) / 2; i++) { if (str.charAt(i) != str.charAt(j)) return false; j--; } return true; } Java Programming: From Problem Analysis to Program Design, 4e 35

  36. Rewrite isPalindrome() Methodusing while loop stmt public static boolean isPalindrome(String str){ int len = str.length(); int i, j; j = len - 1; while (i <= (len - 1) / 2) { if (str.charAt(i) != str.charAt(j)) return false; i++; j--; } return true; } Java Programming: From Problem Analysis to Program Design, 4e 36

  37. Exercises • Write a value-returning method isVowel(), that returns true if a given character is vowel, and otherwise returns false. • Write a Java program to test the method • Write a Java program to output the number of vowels in a string.

  38. The int variable num contains the desired sum to be rolled Java Programming: From Problem Analysis to Program Design, 4e 38

  39. Moore on Java syntax • Classes and Objects

  40. Anatomy of a Class Classes defined inside packages Classes group: Data members Member functions /methods/ All programs consist of at least one class that includes at least one method main() Every class is named C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 40 40

  41. Class Definition • Building block or basic encapsulation constructs of Java object-oriented program. • Every executable statement must be placed inside a method and every method must be placed inside a class. • Classes define a category, or type, of object. • Classes define reference types that are the basic building blocks of Java programs, and they serve as ADT to create objects in OOP C# Programming: From Problem Analysis to Program Design C# Programming: From Problem Analysis to Program Design 41 41

  42. Defining Classes for Objects • An object has both a state and behavior. • The state defines the object. • The behavior defines what the object does. • Data fields define state and methods define behaviors. Additionally, a class provides special type of methods, known as constructors, invoked to construct objects from the class. • Example: • A Circle object has a data field, i.e. radius which is the property to characterize a circle. • One behavior of a circle is that its area can be computed using the method getArea()

  43. Classes

  44. Constructors Constructors are a special kind of methods that are invoked to construct objects. A constructor with no parameters is referred to as a no-arg constructor. Circle() { radius = 0.0; } //---------------------------- Circle(double newRadius) { radius = newRadius; }

  45. Constructors Constructors are a special kind of methods that are invoked to construct objects. A constructor with no parameters is referred to as a no-arg constructor. Circle() { radius = 0.0; } //---------------------------- Circle(double radius) { this.radius = radius; }

  46. Constructor-method with three differences ·       Constructors must have the same name as the class itself. ·       Constructors do not have a return type—not even void. ·       Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.

  47. Default Constructor A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class. 47

  48. Creating Objects Using Constructors Syntax: new ClassName(); Example: To create anonymous objects new Circle() new Circle(5.0)

  49. Declaring Object Reference Variables To reference an object, assign the object (being created using new operator) to a reference variable. To declare a reference variable, use the syntax: ClassName objectRefVar; Example: Circle myCircle;

  50. Declaring/Creating Objectsin a two Steps Circle myCircle; myCircle = new Circle();

More Related