Dr. Amel Ksibi [email protected] Object-oriented programming with JAVA.

Click here to load reader

download Dr. Amel Ksibi amel.ksibi@gmail.com Object-oriented programming with JAVA.

of 96

Transcript of Dr. Amel Ksibi [email protected] Object-oriented programming with JAVA.

  • Slide 1
  • Dr. Amel Ksibi [email protected] Object-oriented programming with JAVA
  • Slide 2
  • PLAN Chapter 1: Object-oriented programming Chapter 2: Java Platform Chapter 3: Java Basics Chapter 4: Advanced java programming
  • Slide 3
  • Chapter 1 Object-Oriented Programming
  • Slide 4
  • A brief history of computing Object orientation paradigm Object oriented principles What is object oriented programming? Benefits of object oriented programming
  • Slide 5
  • A brief history of computing Computing is constantly changing our world and our environment In 1960: mainframes (to manage large volumes of data(numbers) efficienctly.) In 1980: personal computers (to write letters and to manage home accounts) In 1990: WWW (to publish information that could easily be accessed on a global scale) Just as new computing technologies are changing our world so to are new techniques and ideas changing the way we develop computer systems.
  • Slide 6
  • A brief history of computing In 1950: Machine code languages (unsophisticated, complex and machine specific) In 1960: High level languages (programming simpler) development of large complex programs that were difficult to manage and maintain. 1970: Structured programming paradigm (logically structure the programs developed into separate smaller, more manageable components. problems in understanding the systems we need to create Problems in changing existing software as users requirements changed.
  • Slide 7
  • A brief history of computing In 1990: Object oriented paradigm (development of software components where operations and data are modelled together) Re-use of software components in different applications Saving development time and cost saving Systems more maintainable and easier to understand
  • Slide 8
  • Object orientation paradigm
  • Slide 9
  • The OO paradigms suggest we should model instructions in a computer program with the data they manipulate and store these as components together. reusable software components
  • Slide 10
  • Object orientation paradigm
  • Slide 11
  • The OOP paradigm aims to help overcome the following problems: Poor analysis and design: the computer system we create doesnt do the right thing Poor maintability: the system is hard to understand and revise when as is inevitable, requests for change arise.
  • Slide 12
  • Object oriented programming It is a method of programming that involves the creation of intellectual objects that model a business problem we are trying to solve.( e.g. a bank account) With each object, we wodel data associated with it (i.e. its status) and the behaviour associated with it ( what our program should allow that object to do).
  • Slide 13
  • Object oriented programming In creating an object oriented program, we define the properties of a class of objects (e;g; all bank accounts) and then create indivudual objects from this class (e.g. your bank account). classObject 1Object 2Object 3Object 4 A class is a software design which describes the general properties and bihaviours of something Individual objects are created from the class design for each actual thing.
  • Slide 14
  • Object oriented programming Real world Software model Abstraction
  • Slide 15
  • Object Oriented Principles Abstraction allows us to consider complex ideas while ignoring irrelevant detail that would confuse us. Encapsulation allows us to focus on what something does without considering the complexities of how it works. Generalization/specialisation allows us to define general characteristics and operations of an object and allows us to create more specialized versions of this object. The specialized versions of this object will automatically inherit all of the characteristics of the more generalized object. Polymorphism allows the systems to be extended with new specialized objects being created, while allowing current parts of the system to interact with new object without concern for the specific properties of the new objects.
  • Slide 16
  • Benefits of OOP Better abstractions(modelling information and behaviour together) Better maintainability (more comprehensible, less fragile) Better reusability (classes as encapsulated components)
  • Slide 17
  • Object-Oriented langages Java C# C++ PHP 5 Python Ruby
  • Slide 18
  • Chapter 2 Java Platform
  • Slide 19
  • Java - Overview A high-level programming language Originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]). Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications. Java is guaranteed to be Write Once, Run Anywhere.
  • Slide 20
  • Java- Key benefits Object oriented Platform independant Simple Secure architectural-neutral Portable Robust Multithreaded Interpreted High performance Distributed dynamic
  • Slide 21
  • Java- Key benefits Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is interpreted by virtual Machine (JVM) on which ever platform it is being run. Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
  • Slide 22
  • Java- Key benefits Secure: With Java's secure feature it enables to develop virus- free, tamper-free systems. Authentication techniques are based on public-key encryption. Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.
  • Slide 23
  • Java- Key benefits Architectural-neutral :Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system. Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • Slide 24
  • Java- Key benefits High Performance: With the use of Just-In-Time compilers, Java enables high performance. Distributed: Java is designed for the distributed environment of the internet. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Classes are stored in separate files and are loaded into the Java interpreter only when needed. This means that an application can decide as it is running what classes it needs and can load them when it needs them.
  • Slide 25
  • My First program in Java public class Hello { public static void main(String args[]) { System.out.println("Hello World"); }
  • Slide 26
  • Compilers, Interpreters, and the JVM 26 compile interpret source code Compiled Languages (e.g. C, C++) bytecode binary code execute Java interpret source code Interpreted Languages (e.g. JavaScript, Perl, Ruby) Small, easy to write Interpreter is unique to each platform Interpreter translates code into binary and executes it Compiler is unique to each platform JVM is unique to each platform Bytecode is platform independent Java Virtual Machine (JVM)
  • Slide 27
  • Compiling and Running Java 27 Java Code Java Bytecode JRE for Linux JRE for Windows Java compiler Hello.java javac Hello.java Hello.class java Hello Java interpreter (JVM) translates bytecode to machine code in JRE
  • Slide 28
  • Phases of Program Creation and Execution Edit : Creating a Java program consists of using an editor program. Java source code files are saved with the file extension .java. Source files can be created using a simple text editor, or an IDE (Integrated Development Environment), such as JCreator, Eclipse, JBuilder, etc. IDEs provide tools to support the development process, including editors for writing programs and debugging for locating logic errors in programs.
  • Slide 29
  • Phases of Program Creation and Execution Compile During this phase, the programmer compiles the program using a command at the command line, or tools from the IDE. At this step, the Java source code is translated into bytecodes. If you are running the Java compiler from the command prompt, the command to enter is: Command: javac Hello.java* Running this command would compile the Java source file, Hello.java, and generate a bytecode class file named, Hello.class. Compiler is available as part of the Java Development Kit (JDK)
  • Slide 30
  • Phases of Program Creation and Execution Load The program must be placed in memory before it can execute. In loading, the class loader takes the .class files, created in the previous step, and transfers them to primary memory. The class loader also loads the.class files provided by Java, that your program uses.
  • Slide 31
  • Phases of Program Creation and Execution Verify As the classes are loaded, a bytecode verifier examines the bytecodes to ensure they are valid and dont violate any security restrictions. Execute During the last phase, the JVM executes a programs bytecodes, performing the actions specified by the program. Command: java Hello A version of Java Runtime Environment (JRE) which incorporates a JVM is required to execute the bytecode and the Java library packages.
  • Slide 32
  • JRE / JDK JRE: Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution. JDK: It's the full featured Software Development Kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs. Usually, when you only care about running Java programs on your browser or computer you will only install JRE. It's all you need. On the other hand, if you are planning to do some Java programming, you will also need JDK.
  • Slide 33
  • JDK / JRE File Structure c:\jdk1.7.0 Root directory of the JDK software installation. Contains copyright, license, and README files. Also contains src.zip, the archive of source code for the Java platform. c:\jdk1.7.0\bin Executable files for the development tools contained in the Java Development Kit. The PATH environment variable should contain an entry for this directory. c:\jdk1.7.0\jre Root directory of the Java runtime environment used by the JDK development tools. The runtime environment is an implementation of the Java platform. c:\jdk1.7.0\jre\bin Executable files and DLLs for tools and libraries used by the Java platform. c:\jdk1.7.0\jre\lib Code libraries, property settings, and resource files used by the Java runtime environment.
  • Slide 34
  • Getting started In order to get started in Java programming, one needs to get a recent copy of the Java JDK. This can be obtained for free by downloading it from the Sun Microsystems website, http://java.sun.com/ Once you download and install this JDK, you need a text editor to write your source file. Save the file as Hello.java The name of the program has to be similar to the filename. Java is case-sensitive: You cannot name a file Hello.java and then in the program you write public class hello.
  • Slide 35
  • Getting started In order to get the output we have to first compile the program and then execute the compiled class. The applications required for this job are available as part of the JDK: javac.exe compiles the program java.exe the interpreter used to execute the compiled program In order to compile and execute the program we need to switch to the command prompt. On windows systems, this can be done by clicking Start>Run>cmd
  • Slide 36
  • Getting started When you get to the required destination you need to type : c:\[folder name]\javac Hello.java The above command will compile the java file and prompt the user with any errors. If the compilation is successful, a new file containing the bytecode is generated: Hello.class To execute the program, we invoke the interpreter by typing: c:\[folder name]\java Hello The result will be displayed in the DOS window.
  • Slide 37
  • Chapter 3 Java Fondamentals
  • Slide 38
  • My First program in Java public class Hello { public static void main(String args[]) { System.out.println("Hello World"); }
  • Slide 39
  • My First program in Java Understanding first java program o class keyword is used to declare a class in java. o public keyword is an access modifier which represents visibility, it means it is visible to all. o static is a keyword, if we declare any method as static, it is known as static method. The core advantage of static method is that there is no need to create object to invoke the static method. So it saves memory. o void is the return type of the method, it means it doesn't return any value. o main represents startup of the program. o String[] args is used for command line argument. o System.out.println() is used print statement.
  • Slide 40
  • Naming convention Case Sensitivity Java is case sensitive Example: Hello and hello would have different meaning in Java. Class Names For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. Example class MyFirstJavaClass
  • Slide 41
  • Naming convention Method Names All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName()
  • Slide 42
  • Naming convention Program File Name Name of the program file should exactly match the class name. When saving the file, you should save it using the class name and append '.java' to the end of the name. If the file name and the class name do not match your program will not compile Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java
  • Slide 43
  • Java Identifiers All Java components require names. Names used for classes, variables and methods are called identifiers. In Java, there are several points to remember about identifiers. All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character identifiers can have any combination of characters. A key word cannot be used as an identifier. Identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, __1_value Examples of illegal identifiers: 123abc, -salary
  • Slide 44
  • Java Keywords These reserved words may not be used as constant or variable or any other identifier names.
  • Slide 45
  • Comments in Java Java supports single-line and multi-line comments very similar to c and c++. All characters available inside any comment are ignored by Java compiler. public class MyFirstJavaProgram{ /* This is my first java program. * This will print 'Hello World' as the output * This is an example of multi-line comments. */ public static void main(String []args){ // This is an example of single line comment /* This is also an example of single line comment. */ System.out.println("Hello World"); } A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores it.
  • Slide 46
  • Java: Datatypes There are two data types available in Java: Primitive Data Types Reference/Object Data Types
  • Slide 47
  • Java: Datatypes Why char uses 2 byte in java and what is \u0000 ? because java uses unicode system rather than ASCII code system. \u0000 is the lowest range of unicode system.
  • Slide 48
  • Java: Datatypes Examples: int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = 'a'; // the char variable a is initialized with value 'a'
  • Slide 49
  • Java: Variables Variable is name of reserved area allocated in memory. int data=50;//Here data is variable
  • Slide 50
  • Java: Variables Types of variable localinstanceclass A variable that is declared inside the method is called local variable. A variable that is declared inside the class but outside the method is called instance variable. It is not declared as static. A variable that is declared as static is called static (also class) variable. It cannot be local.
  • Slide 51
  • Java: Variables Example to understand the types of variables: class A{ int data=50;//instance variable static int m=100; //static variable void method(){ int n=90; //local variable } } //end of class
  • Slide 52
  • Java: Variables Local variables Local variables are declared in methods. Local variables are created when the method is entered and the variable will be destroyed once it exits the method. Local variables are visible only within the declared method. There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.
  • Slide 53
  • Java: Variables Local variables o Example: public class Test{ public void myAge(){ int age = 0; age = age + 7; System.out.println(My age is : " + age); } public static void main(String args[]) { Test test = new Test(); test.myAge(); } } My age is: 7 public class Test{ public void myAge(){ int age ; age = age + 7; System.out.println(My age is : " + age); } public static void main(String args[]) { Test test = new Test(); test.myAge(); } } Test.java:4:variable number might not have been initialized age = age + 7; ^ 1 error
  • Slide 54
  • Java: Variables Instance variables Instance variables are declared in a class, but outside a method. Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed. Instance variables can be declared in class level before or after use. The instance variables are visible for all methods in the class. Normally, it is recommended to make these variables private (access level).
  • Slide 55
  • Java: Variables Instance variables Instance variables have default values. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However within static methods and different class ( when instance variables are given accessibility) should be called using the fully qualified name. ObjectReference.VariableName.
  • Slide 56
  • Java: Variables Instance variables Example: public class Employee{ // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName){ name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal){ salary = empSal; } // This method prints the employee details. public void printEmp(){ System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]){ Employee empOne = new Employee("Ransika"); empOne.setSalary(1000); empOne.printEmp(); } } name : Ransika salary :1000.0
  • Slide 57
  • Java: Variables Class/Static variables Class variables also known as static variables are declared with the static keyword in a class, but outside a method. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops.
  • Slide 58
  • Java: Variables Class/Static variables Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables. Static variables can be accessed by calling with the class name ClassName.VariableName. When declaring class variables as public static final, then variables names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
  • Slide 59
  • Java: Variables Class/Static variables Example: public class Employee{ // salary variable is a private static variable private static double salary; // DEPARTMENT is a constant public static final String DEPARTMENT = "Development "; public static void main(String args[]){ salary = 1000; System.out.println(DEPARTMENT+"average salary:"+salary); } Development average salary:1000 Note: If the variables are access from an outside class the constant should be accessed as Employee.DEPARTMENT
  • Slide 60
  • Java : Operators Java provides a rich set of operators to manipulate variables: Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Conditional Operator
  • Slide 61
  • Java : Operators Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. OperatorDescription +Addition - Adds values on either side of the operator -Subtraction - Subtracts right hand operand from left hand operand *Multiplication - Multiplies values on either side of the operator /Division - Divides left hand operand by right hand operand %Modulus - Divides left hand operand by right hand operand and returns remainder ++Increment - Increases the value of operand by 1 --Decrement - Decreases the value of operand by 1
  • Slide 62
  • Java : Operators Relational Operators: There are following relational operators supported by Java language OperatorDescription ==Checks if the values of two operands are equal or not, if yes then condition becomes true. !=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. >Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. =Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.