1 / 54

Object Oriented Programming with JAVA

Object Oriented Programming with JAVA. References: •Java JDK6 documentations. http://java.sun.com/javase/ •Java™ How to Program, Sixth Edition Instructor: Haya Sammaneh. History of Java. Java Originally for intelligent consumer-electronic devices (cell phones)

chaman
Download Presentation

Object Oriented Programming 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. Object Oriented ProgrammingwithJAVA References:•Java JDK6 documentations. http://java.sun.com/javase/•Java™ How to Program, Sixth Edition Instructor: Haya Sammaneh

  2. History of Java • Java • Originally for intelligent consumer-electronic devices (cell phones) • Then used for creating Web pages with dynamic content • Now also used for: • Develop large-scale enterprise applications

  3. The Java Programming Language • A high-level language that can be characterized by all of the following: – Simple – Object oriented – Portable – Distributed – High performance – Multithreaded – Robust – Secure

  4. Java life cycle • Java programs normally undergo four phases • Edit • Programmer writes program (and stores program on disk) • Compile • Compiler creates bytecodes from program (.class) • Load • Class loader stores bytecodes in memory • Execute • Interpreter: translates bytecodes into machine language

  5. Java life cycle • Source code (.java) • Compiled into Byte codes(.class) , as (.exe) in c++ – The Java Application Programming Interface (API) • a large collection of ready-made software components. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. – Java Virtual Machine (JVM) – Machine code

  6. Java life, cont..

  7. JVM an Portability • Through the Java VM, the same application is capable of running on multiple platforms.

  8. Java Technology • Java EE vs. Java SE – EE: enterprise edition (web services, distribution, RMI, …) – SE: standard edition (stand alone app.) • Development Tools – The main tools you'll be using are the javac compiler, the java launcher (java), and the javadoc documentation tool. • Application Programming Interface (API) – Java SE Development Kit 6 (JDK 6) – Offers a wide array of useful classes ready for use in your own applications.

  9. Java Technology, cont… • User Interface Toolkits – Swing and Java 2D toolkits to create Graphical User Interfaces (GUIs). • Integration Libraries – Application Programming Interface (API) – Java RMI, and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access.

  10. Before you start • Install the Java SE Development Kit 6 (JDK 6). • Modify the Java Path environment. – Go to the System Properties by right clicking you My Computer and choosing properties Environment variablesclick on TEMP Edit. – Add the path to the java bin directory as shown in the next slid. • Install the Textpad editor which we will use to develop our applications.

  11. Modifying the Path Environment variable.

  12. Hello world • To begin you need a text editor. – Notepad, TextPad, … – Create a new directory on C: name it JavaProjects. • Open new file, save it as HelloWorld.java in new directory HelloWorld inside the JavaProjects Directory. • Write the following code and save the file: class HelloWorld { /*simple java application*/ public static void main(String[] args) { System.out.println(“Hello World”); //displays a string } } • Note: the file name should have the same name as the class

  13. Compiling and running • Assuming the HelloWorld.java is saved in the c:\JavaProjects\HelloWorld directory: • Open the a Console, (startRun…), type cmd. • Type cd \ to return to c:> • Go to the helloworld directry – (cd c:\JavaProjects\HelloWorld) • compile your application – javac HelloWorld.java • Run your application – java HelloWorld.class • Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive

  14. Closer Look • Three primary components: source code comments, the HelloWorld class definition, and the main method. • Comments are ignored by the compiler but are useful to other programmers. • Two supported kinds of comments – /* text */ The compiler ignores everything from /* to */. – // text The compiler ignores everything from // to the end of the line. • The most basic form of a class definition is – class name {…} – Every program must have at least one class, and this class should contain the main method.

  15. Closer Look, cont… • In the Java programming language, every application must contain a main method whose signature is: – public static void main(String[] args) – The modifiers public and static can be written in either order (public static or static public). – You can name the argument anything you want, but most programmers choose "args" or "argv.“ • This is the string array that will contains the command line arrguments. – The main method is the entry point for your application and will subsequently invoke all the other methods required by your program. • System.out.println("Hello World!"); – uses the System class from the API to print the "Hello World!" message to standard output.

  16. Example, Prints.java import java.lang.System; class Prints { public static void main(String[] args) { System.out.print(":Haya "); System.out.println("This Text in one line"); System.out.printf("\nFormated text;\n%s\t%s\n%s\t%d\n%s\t%d\n","Student","Mark","Ahmad",3,"Sami",5); System.out.printf(" %x\n",15); // f System.out.printf(" %o\n",15); // 17 } } • %o for octal, %x for hexadicemal, %f for floating point representations.

  17. Example • Name of class called identifier • Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ ) • Does not begin with a digit, has no spaces • Java is case sensitive • Examples: Print, $Print, _Print, Print7 is valid • 7print is invalid

  18. Summation of two numbersExample import java.util.Scanner; // program uses class Scanner public class Summation { public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; int number2; int sum; System.out.print( "Enter first integer: " ); number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); number2 = input.nextInt(); // read second number from user sum = number1 + number2; // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum

  19. Summation – cont. • import: used to get the library (Java API) contains the definition for the used classes – We need the scanner class defined in java.util.scanner package – All imports must be at the beginning, before class definition. – Using a Java API without importing the required package cause syntax error. – A Scanner enables a program to read data (e.g., numbers). The data can come from many sources, such as a file on disk or the user at the keyboard (System.in). – By default, package java.lang is imported in every Java program, this package contains the definition for “System” class. – We uses Scanner object input's “nextInt” method to obtain an integer from the user at the keyboard.

  20. Object-Oriented Programming Concepts • What Is an Object? • What Is a Class? • What Is Inheritance? • What Is an Interface? • What Is a Package?

  21. What Is an Object? – Real world consists of objects (desk, your television set, your bicycle). – They share two characteristics: They all have state and behavior. • Bicycles have state (current gear, current speed) and behavior (changing gear, applying brakes). – Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation.

  22. What Is an Object? – cont. • Grouping code into individual software objects provides a number of benefits, including: – Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system. – Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world. – Code re-use: If an object already exists , you can use that object in your program. – Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its

  23. What Is a Class? – In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. class Bicycle { int speed = 0; int gear = 1; void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println( speed:"+speed+" gear:"+gear); } }

  24. What Is a Class? – cont. • Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods: class BicycleDemo { public static void main(String[] args) { // Create two different Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.speedUp(10); bike2.changeGear(2); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } }

  25. What Is Inheritance? • Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. • The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // new fields and methods defining a mountain bike // would go here }

  26. What Is an Interface? • An interface is a group of related methods with empty bodies. interface Bicycle { void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } • To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of this class implemented as before }

  27. What Is a Package? • A package is a namespace that organizes a set of related classes and interfaces. • you can think of packages as being similar to different folders on your computer.

  28. Language Basics • Variables • Operators • Expressions, Statements, and Blocks • Control Flow Statements

  29. Variables Four kinds: – Instance Variables (Non-Static Fields). • Values are unique to each instance (object) of a class – Class Variables (Static Fields). • There is exactly one copy of this variable in existence. – Local Variables. – Parameters.

  30. Variables – Naming • Variable names are case sensitive. • Can be any legal identifier an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign, "$", or the underscore character, "_". • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. Ex: GearRatio

  31. Variables - Primitive Data Types • byte: 8-bit signed integer. • short : 16-bit signed integer • int: 32-bit signed integer • long: 64-bit signed integer

  32. Variables - Primitive Data Types • float: 32-bit – This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. • double: 64-bit • boolean: has only two possible values: true and false. • char:The char data type is a single 16-bit Unicode character. ('\u0000' (or 0) to '\uffff' (or 65,535). • String object; for example, String s = "this is a string";. Once created, their values cannot be changed.

  33. Literals – Ex: boolean result = true; char capitalC = 'C' ; byte b = 100; short s =10000; int i = 100000; • int: – int decVal = 26; // The number 26, in decimal – int hexVal = 0x1a; // The number 26, in hexadecimal • float and double: – E or e (for scientific notation) – F or f (32-bit float literal) – D or d (64-bit double literal). – double d1 = 123.4; – double d2 = 1.234e2; // same value as d1, but in scientific notation – float f1 = 123.4f;

  34. Literals – cont. • char and String: – char ch='\u0108‘;

  35. Arrays • An array is a container object. • Each item in an array is called an element, and each element is accessed by its numerical index. • Declaring a Variable to Refer to an Array – type[] <arrayname>; – Ex: • int[] arrayOfIntegers; • float arrayOfFloats[ ]; // this form is discouraged • Creating, Initializing, and Accessing an Array – <array_name>=new type[<size>]; – Ex: • arrayOfIntegers = new int[10]; // create an array of integers • Or you can create and initialize at the same time: • int[] anArray = {100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

  36. Multidimensional Arrays • int b[][] = { { 1, 2 }, { 3, 4, 5 } }; • int b[][]; b = new int [ 3 ][ 4 ]; • int b[][]; b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

  37. Operator

  38. Operators – cont. • The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo class ConcatDemo { public static void main(String[] args) { String firstString = "This is"; String secondString = " a concatenated string."; String thirdString = firstString+secondString; System.out.println(thirdString); } }

  39. Expressions, Statements, and Blocks • An expression is a construct made up of variables, operators, and method invocations. 1 * 2 * 3 x + y / 100 // ambiguous (x + y) / 100 // unambiguous, recommended x + (y / 100) // unambiguous, recommended • A statement forms a complete unit of execution. aValue = 8933.234; // assignment statement aValue++; // increment statement System.out.println("Hello World!"); // method invocation // statement Bicycle myBike = new Bicycle(); // object creation // statement

  40. Expressions, Statements, and Blocks • A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. class BlockDemo { public static void main(String[] args) { boolean condition = true; if (condition) { // begin block 1 System.out.println("Condition is true."); } // end block one else { // begin block 2 System.out.println("Condition is false."); } // end block 2 } }

  41. Control Flow Statements • Decision-making statements – if, if-else, switch • The looping statements – for, while, do – while • The branching statements – break, continue, return

  42. Decision-making statements . void applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must be moving currentSpeed--; // the "then" clause: // decrease current speed } } • The opening and closing braces are optional, provided that the "then" clause contains only one statement void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } }

More Related