Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-oriented programming with JAVA

Similar presentations


Presentation on theme: "Object-oriented programming with JAVA"— Presentation transcript:

1 Object-oriented programming with JAVA
Dr. Amel Ksibi

2 PLAN Chapter 1: Object-oriented programming Chapter 2: Java Platform
Chapter 3: Java Basics Chapter 4: Advanced java programming

3 Chapter 1 Object-Oriented Programming

4 Object-Oriented Programming
A brief history of computing Object orientation paradigm Object oriented principles What is object oriented programming? Benefits of object oriented programming

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.

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.

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

8 Object orientation paradigm

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

10 Object orientation paradigm

11 Object orientation paradigm
The OOP paradigm aims to help overcome the following problems: Poor analysis and design: the computer system we create doesn’t do the right thing Poor maintability: the system is hard to understand and revise when as is inevitable, requests for change arise.

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

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). class Object 1 Object 2 Object 3 Object 4 Individual objects are created from the class design for each actual thing. A class is a software design which describes the general properties and bihaviours of something

14 Object oriented programming
Software model Abstraction Real world

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.

16 Benefits of OOP Better abstractions(modelling information and behaviour together) Better maintainability (more comprehensible , less fragile) Better reusability (classes as encapsulated components)

17 Object-Oriented langages
Java C# C++ PHP 5 Python Ruby

18 Chapter 2 Java Platform

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. This tutorial gives a complete understanding of Java. This reference will take you through simple and practical approach while learning Java Programming language.

20 Java- Key benefits Object oriented Robust Platform independant
Multithreaded Simple Interpreted Secure High performance architectural-neutral Distributed Portable dynamic Java is: 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 distributed over the web and interpreted by virtual Machine (JVM) on whichever 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. Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. 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. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset. Robust:Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications. 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. 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. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

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.

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.

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.

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.

25 My First program in Java
public class Hello { public static void main(String args[]) { System.out.println("Hello World"); }

26 Compilers, Interpreters, and the JVM
Compiled Languages (e.g. C, C++) compile execute source code binary code Compiler is unique to each platform Interpreted Languages (e.g. JavaScript, Perl, Ruby) Interpreter translates code into binary and executes it interpret source code Small, easy to write Interpreter is unique to each platform Java Bytecode is platform independent source code compile interpret bytecode JVM is unique to each platform Java Virtual Machine (JVM)

27 Compiling and Running Java
Code 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

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. During the creation and execution of a Java program, programs normally go through 5 phases.  These are:

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) During the creation and execution of a Java program, programs normally go through 5 phases.  These are:

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. During the creation and execution of a Java program, programs normally go through 5 phases.  These are:

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 don’t 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. During the creation and execution of a Java program, programs normally go through 5 phases.  These are:

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.

33 JDK / JRE File Structure
c:\jdk 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.

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, 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”.

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

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.

37 Chapter 3 Java Fondamentals

38 My First program in Java
public class Hello { public static void main(String args[]) { System.out.println("Hello World"); }

39 My First program in Java
Understanding first java program class keyword is used to declare a class in java. public keyword is an access modifier which represents visibility, it means it is visible to all. 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. void is the return type of the method, it means it doesn't return any value. main represents startup of the program. String[] args is used for command line argument. System.out.println() is used print statement.

40 Naming convention Case Sensitivity Class Names 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

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

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‘

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

44 Java Keywords These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while

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.

46 Java: Datatypes There are two data types available in Java:
Primitive Data Types Reference/Object Data Types

47 Java: Datatypes Data Type Default Value Default size boolean false
1 bit char '\u0000' 2 byte byte 1 byte short int 4 byte long 0L 8 byte float 0.0f double 0.0d 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.

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 = ; // declares and assigns a value of PI. char a = 'a'; // the char variable a is initialized with value 'a'

49 Java: Variables Variable is name of reserved area allocated in memory.
int data=50;//Here data is variable

50 Java: Variables Types of variable local instance class 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. A variable that is declared inside the method is called local variable.

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

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.

53 Java: Variables Local variables Example: public class Test{ int age ;
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(); } Test.java:4:variable number might not have been initialized My age is: 7 ^ 1 error

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

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.

56 Java: Variables Instance variables Example: name : Ransika
// This method prints the employee details. public void printEmp(){ Example: System.out.println("name : " + name ); public class Employee{ System.out.println("salary :" + salary); } // this instance variable is visible for any child class. public static void main(String args[]){ public String name; Employee empOne = new Employee("Ransika"); // salary variable is visible in Employee class only. empOne.setSalary(1000); private double salary; empOne.printEmp(); // The name variable is assigned in the constructor. } } public Employee (String empName){ name = empName; } name : Ransika // The salary variable is assigned a value. salary :1000.0 public void setSalary(double empSal){ salary = empSal; }

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.

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.

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

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

61 Java : Operators Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. Operator Description + 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

62 Java : Operators Relational Operators:
There are following relational operators supported by Java language Operator Description == 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 less 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. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

63 Java : Operators The Bitwise Operators:
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13; now in binary format : a = b = a&b = a|b = a^b = ~a  =

64 Java : Operators Logical Operators: Operator Description &&
Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. || Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

65 Java : Operators The Assignment Operators: Operator Description =
Simple assignment operator, Assigns values from right side operands to left side operand += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

66 Java : Operators Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. The goal of the operator is to decide which value should be assigned to the variable. Syntax: variable x = (expression) ? value if true : value if false Example: int a , b; a = 10; b = (a == 1) ? 20: 30; System.out.println( "Value of b is : " + b ); b = (a == 10) ? 20: 30;  Value of b is : 30 Value of b is : 20

67 Java : Objects & Classes
A Java program can be defined as a collection of objects that communicate via invoking each other's methods. Object Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. If you compare the software object with a real world object, they have very similar characteristics. A software object's state is stored in fields and behavior is shown via methods. An object is an instance of a class.

68 Java : Objects & Classes
A class can be defined as a template that describes the behaviors /states that object of its type support. Anatomy of a Java Class: Pubic class MyClass { Class body: variables, methods } Access modifier Keyword class Name of the class NO semi-colon

69 Java : Objects & Classes
Example: public class Dog{ String breed; int age; String color; void barking(){ } void hungry(){ } void sleeping(){ } } variables methods

70 Java : Objects & Classes
All objects of a class have the same methods. All objects of a class have the same attributes (i.e., name, type, and number). For different objects, each attribute can hold a different value. The values of the attributes define the object state, which is what makes each object unique.

71 Java : Objects & Classes
A class definition implements the class model. The class behaviors/services/actions/operations are implemented by class methods. The class attributes (data items) are called fields or instance variables. In Java, classes are defined in files with the “.java” extension. The name of the file must match the name of the class defined within it. e.g. class ‘Baker’ must be in Baker.java

72 Java : Objects & Classes
Attributes An attribute is basically a state. Anatomy of an Attribute: <modifier> <type> <name> [ = <initial_value>]; Examples: public class Foo { private int x; private float y = F; private String name = "Bates Motel"; }

73 Java : Objects & Classes
Methods A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Methods operate on the internal state of an object. Object-to-object communication is done via methods.

74 Java : Objects & Classes
Methods Anatomy of a Method: public double getSalary (String name) { } Access modifier Return type Name of the method Parameters Method code: local variables and statements

75 Java : Objects & Classes
Methods Examples: public class Dog { private int weight; public int getWeight() { return weight; } public void setWeight(int x) { weight = x;

76 Java : Objects & Classes
Constructors Every class has a constructor. Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that they should have the same name as the class. A class can have more than one constructor.

77 Java : Objects & Classes
Constructors If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. The default constructor takes no arguments The default constructor has no body It Enables you to create object instances with new Xxx()without having to write a constructor.

78 Java : Objects & Classes
Constructors Example: public class Puppy{ public Puppy(){ } public Puppy(String name){ // This constructor has one parameter, name. }

79 Java : Objects & Classes
Creating an Object: Basically, an object is created from a class. The 'new' keyword is used to create a new object. There are three steps when creating an object from a class: Declaration: To declare an object, you just declare a variable( its type and name) to refer to that object. Instantiation: The ‘new’ operator instantiates a class by allocating memory for a new object of that type. Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object.

80 Java : Objects & Classes
Creating an Object: (more details) Object Declaration: To declare an object, you just declare a variable( its type and name) to refer to that object. In Java, classes can be used as data types. So, type can be the name of a class. Classes are reference types. Declarations notify the compiler that you will use name to refer to a variable whose type is type. Declarations do not create new objects.

81 Java : Objects & Classes
Creating an Object: Example: public class Dog{ Private String name; public Dog(String nameDog){ // This constructor has one parameter, name. name=nameDog; } public static void main(String[]args){ // Following statement would create an object myDog Dog myDog =new Dog("tommy");

82 Java : Objects & Classes
Accessing Instance Variables and Methods Instance variables and methods are accessed via created objects. The “dot” notation: <object>.<member> This is used to access object members including attributes and methods. Examples: d.setWeight(42); d.weight = 42; // only permissible : if weight is public

83 Java : Objects & Classes
Accessing Instance Variables and Methods /* Call class method to set puppy's age */ public class Puppy{ myPuppy.setAge(2); /* Call another class method to get puppy's age */ int puppyAge; myPuppy.getAge(); public Puppy(String name){ /* You can access instance variable as follows as well */ // This constructor has one parameter, name. System.out.println(myPuppy.puppyAge ); } } System.out.println("Name is :"+ name); } public void setAge(int age ){ puppyAge = age; } public int getAge(){ System.out.println(puppyAge ); return puppyAge; } public static void main(String[]args){ /* Object creation */ Puppy myPuppy =new Puppy("tommy");

84 Java : Objects & Classes
Encapsulation: Information hiding The problem: Client code has direct access to internal data: MyDate d = new MyDate(); d.day = 32; // invalid day d.month = 2; d.day = 30; // reasonable but wrong d.day = d.day + 1; // no check for wrap around MyDay day month year

85 Java : Objects & Classes
Encapsulation: Information hiding The Solution: Client code must use setters/getters to access internal data: MyDate d = new MyDate(); d.setDay(32); // invalid day, returns false d.setMonth(2); d.setDay(30); // plausible but wrong d.setDay(d.getDay() + 1); MyDay day month year setDay( : Integer) : Void setMonth( : Integer) : Void setYear( : Integer) : Void getDay() : Integer getMonth() : Integer getYear() : Integer Verify days in month

86 Java : Objects & Classes
Encapsulation Encapsulation is one of the four fundamental OOP concepts. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Encapsulation is also referred to as data hiding.

87 Java : Objects & Classes
Encapsulation Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. Benefits of Encapsulation: The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. Encapsulation gives maintainability, flexibility and extensibility to our code.

88 Java : Objects & Classes
Encapsulation

89 Java : Objects & Classes
Source file layout Example, the VehicleReport.java file: Basic syntax of a Java source file: package shipping.reports; import shipping.domain.*; [< package_declaration>] import java.util.List; [< import_declarations>] import java.io.*; public class VehicleReport { < class_declaration>+ private List vehicles; public void generateReport() {...} }

90 Java : Objects & Classes
Packages Packages help manage large software systems. Packages can contain classes and sub-packages.

91 Java : Objects & Classes
Packages Basic syntax of the package statement: package < top_pkg_name>[.< sub_pkg_name>]*; Example: package shipping.reports; Specify the package declaration at the beginning of the source file. Only one package declaration per source file. If no package is declared, then the class “belongs” to the default package. Package names must be hierarchical and separated by dots.

92 Java : Objects & Classes
« Import » Statement Basic syntax of the import statement: Import <pkg_name>[.<sub_pkg_name>].<class_name>; OR import <pkg_name>[.< sub_pkg_name>].*; Examples: import shipping.domain.*; import java.util.List; import java.io.*; Precedes all class declarations Tells the compiler where to find classes to use

93 Java : Objects & Classes
Directory layout and packages Packages are stored in the directory tree containing the package name. Example, the “shipping” application packages:

94 Java : Objects & Classes
Source file declaration rules There can be only one public class per source file. A source file can have multiple non public classes. The public class name should be the name of the source file as well which should be appended by .java at the end. If the class is defined inside a package, then the package statement should be the first statement in the source file. If import statements are present then they must be written between the package statement and the class declaration. If there are no package statements then the import statement should be the first line in the source file. Import and package statements will imply to all the classes present in the source file. It is not possible to declare different import and/or package statements to different classes in the source file.

95

96


Download ppt "Object-oriented programming with JAVA"

Similar presentations


Ads by Google