SlideShare a Scribd company logo
1 of 95
PLAN
 Chapter 1: Object-oriented programming
 Chapter 2: Java Platform
 Chapter 3: Java Basics
 Chapter 4: Advanced java programming
Chapter 1
Object-Oriented Programming
Object-Oriented Programming
A brief history of computing
Object orientation paradigm
Object oriented principles
What is object oriented
programming?
Benefits of object oriented
programming
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.
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.
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
Object orientation paradigm
 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
Object orientation paradigm
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.
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).
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
…
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.
Object oriented programming
Real
world
Software
model
Abstraction
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.
Benefits of OOP
 Better abstractions(modelling information and
behaviour together)
 Better maintainability (more comprehensible , less
fragile)
 Better reusability (classes as encapsulated
components)
Object-Oriented langages
 Java
 C#
 C++
 PHP 5
 Python
 Ruby
 …
Chapter 2
Java Platform
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.
Java- Key benefits
 Object oriented
 Platform independant
 Simple
 Secure
 architectural-neutral
 Portable
 Robust
 Multithreaded
 Interpreted
 High performance
 Distributed
 dynamic
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.
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.
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
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.
My First program in Java
public class Hello {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
Compilers, Interpreters, and the JVM
25
compile
compile interpret
source code
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)
Compiling and Running Java
26
Java
Code
Java
Bytecode
JRE for Linux
JRE for
Windows
Java compiler
Hello.java
javac Hello.java
Hello.class
Java interpreter (JVM)
translates bytecode to
machine code in JRE
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.
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)
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.
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.
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.
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.0bin 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.0jre 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.0jrebin Executable files and DLLs for tools and
libraries used by the Java platform.
 c:jdk1.7.0jrelib Code libraries, property settings, and resource
files used by the Java runtime environment.
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”.
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
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.
Chapter 3
Java Fondamentals
My First program in Java
public class Hello {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
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.
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
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()
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‘
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
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 synchroniz
ed
this throw
throws transient try void
volatile while
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.
Java: Datatypes
 There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types
Java: Datatypes
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
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.
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'
Java: Variables
 Variable is name of reserved area allocated in
memory.
 int data=50;//Here data is variable
Java: Variables
Types of variable
local instance class
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.
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
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.
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
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).
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.
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
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.
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.
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
Java : Operators
 Java provides a rich set of operators to
manipulate variables:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Conditional Operator
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
Java : Operators
 Relational Operators:
There are following relational operators supported by
Java language
Operato
r
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
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 = 0011 1100
 b = 0000 1101
 a&b = 0000 1100
 a|b = 0011 1101
 a^b = 0011 0001
 ~a = 1100 0011
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.
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
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;
System.out.println( "Value of b is : " + b );
 Value of b is : 30
Value of b is : 20
Java : Objects & Classes
 A Java program can be defined as a collection of
objects that communicate via invoking each other's
methods.
 Object
o Objects have states and behaviors.
o Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating.
o If you compare the software object with a real world
object, they have very similar characteristics.
o A software object's state is stored in fields and behavior
is shown via methods.
o An object is an instance of a class.
Java : Objects & Classes
 Class
o A class can be defined as a template that describes
the behaviors /states that object of its type support.
o Anatomy of a Java Class:
Pubic class MyClass
{
Class body: variables, methods
} NO semi-colon
Access
modifier
Keyword
class
Name of the
class
Java : Objects & Classes
 Class
o Example:
public class Dog{
String breed;
int age;
String color;
void barking(){ }
void hungry(){ }
void sleeping(){ }
}
methods
variables
Java : Objects & Classes
 Class
o All objects of a class have the same methods.
o All objects of a class have the same attributes
o (i.e., name, type, and number).
o For different objects, each attribute can hold a
different value.
o The values of the attributes define the object state,
which is what makes each object unique.
Java : Objects & Classes
 Class
o A class definition implements the class model.
o The class behaviors/services/actions/operations are implemented by
class methods.
o The class attributes (data items) are called fields or instance variables.
o In Java, classes are defined in files with the “.java” extension.
o The name of the file must match the name of the class defined
within it.
o e.g. class ‘Baker’ must be in Baker.java
Java : Objects & Classes
 Attributes
o An attribute is basically a state.
o Anatomy of an Attribute:
<modifier> <type> <name> [ = <initial_value>];
o Examples:
public class Foo {
private int x;
private float y = 10000.0F;
private String name = "Bates Motel";
}
Java : Objects & Classes
 Methods
o A method is basically a behavior.
o A class can contain many methods. It is in methods
where the logics are written, data is manipulated and
all the actions are executed.
o Methods operate on the internal state of an object.
o Object-to-object communication is done via methods.
Java : Objects & Classes
Method code: local variables and
statements
 Methods
o Anatomy of a Method:
public double getSalary (String
name)
{
}
Access modifier Return type
Name of the
method
Parameters
Java : Objects & Classes
 Methods
o Examples:
public class Dog {
private int weight;
public int getWeight() {
return weight;
}
public void setWeight(int x) {
weight = x;
}
}
Java : Objects & Classes
 Constructors
o Every class has a constructor.
o Each time a new object is created, at least one constructor
will be invoked.
o The main rule of constructors is that they should have the
same name as the class.
o A class can have more than one constructor.
Java : Objects & Classes
 Constructors
o If we do not explicitly write a constructor for a class, the
Java compiler builds a default constructor for that class.
o The default constructor takes no arguments
o The default constructor has no body
o It Enables you to create object instances with new
Xxx()without having to write a constructor.
Java : Objects & Classes
 Constructors
o Example:
public class Puppy{
public Puppy(){ }
public Puppy(String name){
// This constructor has one parameter, name.
}
}
 Creating an Object:
o Basically, an object is created from a class. The 'new' keyword is
used to create a new object.
o There are three steps when creating an object from a class:
o Declaration: To declare an object, you just declare a variable( its
type and name) to refer to that object.
o Instantiation: The ‘new’ operator instantiates a class by allocating
memory for a new object of that type.
o Initialization: The 'new' keyword is followed by a call to a
constructor. This call initializes the new object.
Java : Objects & Classes
 Creating an Object: (more details)
o Object Declaration:
o To declare an object, you just declare a variable( its
type and name) to refer to that object.
o In Java, classes can be used as data types. So, type
can be the name of a class.
o Classes are reference types.
o Declarations notify the compiler that you will use name
to refer to a variable whose type is type.
o Declarations do not create new objects.
Java : Objects & Classes
 Creating an Object:
o 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");
}
}
Java : Objects & Classes
 Accessing Instance Variables and Methods
o Instance variables and methods are accessed via created
objects.
o The “dot” notation:
<object>.<member>
o This is used to access object members including attributes and
methods.
o Examples:
d.setWeight(42);
d.weight = 42; // only permissible : if weight is public
Java : Objects & Classes
 Accessing Instance Variables and
Methods
public class Puppy{
int puppyAge;
public Puppy(String name){
// This constructor has one parameter, name.
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");
/* Call class method to set puppy's age */
myPuppy.setAge(2);
/* Call another class method to get puppy's
age */
myPuppy.getAge();
/* You can access instance variable as follows
as well */
System.out.println(myPuppy.puppyA
ge ); } }
Java : Objects & Classes
 Encapsulation: Information hiding
o 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
Java : Objects & Classes
MyDay
 day
 month
 year
 Encapsulation: Information hiding
o 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);
Java : Objects & Classes
MyDay
 day
 month
 year
setDay( : Integer) :
Void
setMonth( : Integer) :
Void
setYear( : Integer) :
Void
getDay() : Integer
Verify days in month
 Encapsulation
o Encapsulation is one of the four fundamental OOP
concepts.
o Encapsulation is the technique of making the fields in a class
private and providing access to the fields via public methods.
o If a field is declared private, it cannot be accessed by anyone outside
the class, thereby hiding the fields within the class.
o Encapsulation is also referred to as data hiding.
Java : Objects & Classes
 Encapsulation
o Encapsulation can be described as a protective barrier that
prevents the code and data being randomly accessed by other code
defined outside the class.
o Access to the data and code is tightly controlled by an interface.
o Benefits of Encapsulation:
o The fields of a class can be made read-only or write-only.
o A class can have total control over what is stored in its fields.
Encapsulation gives maintainability, flexibility and extensibility to our
code.
Java : Objects & Classes
 Encapsulation
Java : Objects & Classes
 Source file layout
o Basic syntax of a Java source
file:
[< package_declaration>]
[< import_declarations>]
< class_declaration>+
o Example, the
VehicleReport.java file:
package shipping.reports;
import shipping.domain.*;
import java.util.List;
import java.io.*;
public class VehicleReport {
private List vehicles;
public void generateReport()
{...}
}
Java : Objects & Classes
 Packages
 Packages help manage large software systems.
 Packages can contain classes and sub-packages.
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.
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
Java : Objects & Classes
 Directory layout and packages
 Packages are stored in the directory tree containing the
package name.
 Example, the “shipping” application packages:
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.
Java : Objects & Classes
Object oriented programming
Object oriented programming

More Related Content

What's hot

1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology dM Technologies
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overviewJong Soon Bok
 
Introduction to Java Programming
Introduction to Java Programming Introduction to Java Programming
Introduction to Java Programming Saravanakumar R
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruitersph7 -
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Sandeep Rawat
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1RubaNagarajan
 
J2EE Struts with Hibernate Framework
J2EE Struts with Hibernate FrameworkJ2EE Struts with Hibernate Framework
J2EE Struts with Hibernate Frameworkmparth
 
Advanced programming ch1
Advanced programming ch1Advanced programming ch1
Advanced programming ch1Gera Paulos
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSaba Ameer
 
Java presentation
Java presentationJava presentation
Java presentationsurajdmk
 

What's hot (15)

1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology
 
An introduction to java programming language forbeginners(java programming tu...
An introduction to java programming language forbeginners(java programming tu...An introduction to java programming language forbeginners(java programming tu...
An introduction to java programming language forbeginners(java programming tu...
 
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
 
Introduction to Java Programming
Introduction to Java Programming Introduction to Java Programming
Introduction to Java Programming
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruiters
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1
 
J2EE Struts with Hibernate Framework
J2EE Struts with Hibernate FrameworkJ2EE Struts with Hibernate Framework
J2EE Struts with Hibernate Framework
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
Advanced programming ch1
Advanced programming ch1Advanced programming ch1
Advanced programming ch1
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java
JavaJava
Java
 
Java presentation
Java presentationJava presentation
Java presentation
 

Similar to Object oriented programming

Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to JavaDevaKumari Vijay
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDFGeekster
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java SlidesVinit Vyas
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Java Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage EssayJava Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage EssayLiz Sims
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxSuganthiDPSGRKCW
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxDrPreethiD1
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unitgowher172236
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java LanguagePawanMM
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxVeerannaKotagi1
 
java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docxvikasbagra9887
 
TechSearchWeb Tutorials.pdf
TechSearchWeb Tutorials.pdfTechSearchWeb Tutorials.pdf
TechSearchWeb Tutorials.pdfTechSearchWeb
 
Java Evolution-2.pdf
Java Evolution-2.pdfJava Evolution-2.pdf
Java Evolution-2.pdfkumari36
 

Similar to Object oriented programming (20)

Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Java presentation
Java presentationJava presentation
Java presentation
 
Java Introduction | PDF
Java Introduction |  PDFJava Introduction |  PDF
Java Introduction | PDF
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java Slides
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
Java Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage EssayJava Is A Programming Dialect And Registering Stage Essay
Java Is A Programming Dialect And Registering Stage Essay
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Notes of java first unit
Notes of java first unitNotes of java first unit
Notes of java first unit
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
MODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptxMODULE_1_The History and Evolution of Java.pptx
MODULE_1_The History and Evolution of Java.pptx
 
java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docx
 
TechSearchWeb Tutorials.pdf
TechSearchWeb Tutorials.pdfTechSearchWeb Tutorials.pdf
TechSearchWeb Tutorials.pdf
 
Java Evolution-2.pdf
Java Evolution-2.pdfJava Evolution-2.pdf
Java Evolution-2.pdf
 

More from Fraboni Ec

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreadingFraboni Ec
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreadingFraboni Ec
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherenceFraboni Ec
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data miningFraboni Ec
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data miningFraboni Ec
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discoveryFraboni Ec
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching worksFraboni Ec
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cacheFraboni Ec
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsFraboni Ec
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and pythonFraboni Ec
 
Abstract data types
Abstract data typesAbstract data types
Abstract data typesFraboni Ec
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsFraboni Ec
 
Abstraction file
Abstraction fileAbstraction file
Abstraction fileFraboni Ec
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysisFraboni Ec
 
Abstract class
Abstract classAbstract class
Abstract classFraboni Ec
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with javaFraboni Ec
 

More from Fraboni Ec (20)

Hardware multithreading
Hardware multithreadingHardware multithreading
Hardware multithreading
 
Lisp
LispLisp
Lisp
 
What is simultaneous multithreading
What is simultaneous multithreadingWhat is simultaneous multithreading
What is simultaneous multithreading
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Object model
Object modelObject model
Object model
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Abstract class
Abstract classAbstract class
Abstract class
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 

Recently uploaded (20)

The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 

Object oriented programming

  • 1. PLAN  Chapter 1: Object-oriented programming  Chapter 2: Java Platform  Chapter 3: Java Basics  Chapter 4: Advanced java programming
  • 3. Object-Oriented Programming A brief history of computing Object orientation paradigm Object oriented principles What is object oriented programming? Benefits of object oriented programming
  • 4. 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.
  • 5. 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.
  • 6. 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.  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  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.
  • 11. 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).
  • 12. 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 … 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.
  • 14. 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.
  • 15. Benefits of OOP  Better abstractions(modelling information and behaviour together)  Better maintainability (more comprehensible , less fragile)  Better reusability (classes as encapsulated components)
  • 16. Object-Oriented langages  Java  C#  C++  PHP 5  Python  Ruby  …
  • 18. 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.
  • 19. Java- Key benefits  Object oriented  Platform independant  Simple  Secure  architectural-neutral  Portable  Robust  Multithreaded  Interpreted  High performance  Distributed  dynamic
  • 20. 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.
  • 21. 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.
  • 22. 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
  • 23. 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.
  • 24. My First program in Java public class Hello { public static void main(String args[]) { System.out.println("Hello World"); } }
  • 25. Compilers, Interpreters, and the JVM 25 compile compile interpret source code 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)
  • 26. Compiling and Running Java 26 Java Code Java Bytecode JRE for Linux JRE for Windows Java compiler Hello.java javac Hello.java Hello.class Java interpreter (JVM) translates bytecode to machine code in JRE
  • 27. 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.
  • 28. 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)
  • 29. 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.
  • 30. 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.
  • 31. 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.
  • 32. 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.0bin 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.0jre 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.0jrebin Executable files and DLLs for tools and libraries used by the Java platform.  c:jdk1.7.0jrelib Code libraries, property settings, and resource files used by the Java runtime environment.
  • 33. 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”.
  • 34. 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
  • 35. 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. My First program in Java public class Hello { public static void main(String args[]) { System.out.println("Hello World"); } }
  • 38. 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.
  • 39. 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
  • 40. 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()
  • 41. 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‘
  • 42. 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
  • 43. 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 synchroniz ed this throw throws transient try void volatile while
  • 44. 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.
  • 45. Java: Datatypes  There are two data types available in Java:  Primitive Data Types  Reference/Object Data Types
  • 46. Java: Datatypes Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte 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.
  • 47. 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'
  • 48. Java: Variables  Variable is name of reserved area allocated in memory.  int data=50;//Here data is variable
  • 49. Java: Variables Types of variable local instance class 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.
  • 50. 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
  • 51. 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.
  • 52. 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
  • 53. 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).
  • 54. 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.
  • 55. 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
  • 56. 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.
  • 57. 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.
  • 58. 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
  • 59. Java : Operators  Java provides a rich set of operators to manipulate variables: Arithmetic Operators Relational Operators Bitwise Operators Logical Operators Assignment Operators Conditional Operator
  • 60. 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
  • 61. Java : Operators  Relational Operators: There are following relational operators supported by Java language Operato r 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
  • 62. 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 = 0011 1100  b = 0000 1101  a&b = 0000 1100  a|b = 0011 1101  a^b = 0011 0001  ~a = 1100 0011
  • 63. 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.
  • 64. 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
  • 65. 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; System.out.println( "Value of b is : " + b );  Value of b is : 30 Value of b is : 20
  • 66. Java : Objects & Classes  A Java program can be defined as a collection of objects that communicate via invoking each other's methods.  Object o Objects have states and behaviors. o Example: A dog has states - color, name, breed as well as behaviors -wagging, barking, eating. o If you compare the software object with a real world object, they have very similar characteristics. o A software object's state is stored in fields and behavior is shown via methods. o An object is an instance of a class.
  • 67. Java : Objects & Classes  Class o A class can be defined as a template that describes the behaviors /states that object of its type support. o Anatomy of a Java Class: Pubic class MyClass { Class body: variables, methods } NO semi-colon Access modifier Keyword class Name of the class
  • 68. Java : Objects & Classes  Class o Example: public class Dog{ String breed; int age; String color; void barking(){ } void hungry(){ } void sleeping(){ } } methods variables
  • 69. Java : Objects & Classes  Class o All objects of a class have the same methods. o All objects of a class have the same attributes o (i.e., name, type, and number). o For different objects, each attribute can hold a different value. o The values of the attributes define the object state, which is what makes each object unique.
  • 70. Java : Objects & Classes  Class o A class definition implements the class model. o The class behaviors/services/actions/operations are implemented by class methods. o The class attributes (data items) are called fields or instance variables. o In Java, classes are defined in files with the “.java” extension. o The name of the file must match the name of the class defined within it. o e.g. class ‘Baker’ must be in Baker.java
  • 71. Java : Objects & Classes  Attributes o An attribute is basically a state. o Anatomy of an Attribute: <modifier> <type> <name> [ = <initial_value>]; o Examples: public class Foo { private int x; private float y = 10000.0F; private String name = "Bates Motel"; }
  • 72. Java : Objects & Classes  Methods o A method is basically a behavior. o A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. o Methods operate on the internal state of an object. o Object-to-object communication is done via methods.
  • 73. Java : Objects & Classes Method code: local variables and statements  Methods o Anatomy of a Method: public double getSalary (String name) { } Access modifier Return type Name of the method Parameters
  • 74. Java : Objects & Classes  Methods o Examples: public class Dog { private int weight; public int getWeight() { return weight; } public void setWeight(int x) { weight = x; } }
  • 75. Java : Objects & Classes  Constructors o Every class has a constructor. o Each time a new object is created, at least one constructor will be invoked. o The main rule of constructors is that they should have the same name as the class. o A class can have more than one constructor.
  • 76. Java : Objects & Classes  Constructors o If we do not explicitly write a constructor for a class, the Java compiler builds a default constructor for that class. o The default constructor takes no arguments o The default constructor has no body o It Enables you to create object instances with new Xxx()without having to write a constructor.
  • 77. Java : Objects & Classes  Constructors o Example: public class Puppy{ public Puppy(){ } public Puppy(String name){ // This constructor has one parameter, name. } }
  • 78.  Creating an Object: o Basically, an object is created from a class. The 'new' keyword is used to create a new object. o There are three steps when creating an object from a class: o Declaration: To declare an object, you just declare a variable( its type and name) to refer to that object. o Instantiation: The ‘new’ operator instantiates a class by allocating memory for a new object of that type. o Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Java : Objects & Classes
  • 79.  Creating an Object: (more details) o Object Declaration: o To declare an object, you just declare a variable( its type and name) to refer to that object. o In Java, classes can be used as data types. So, type can be the name of a class. o Classes are reference types. o Declarations notify the compiler that you will use name to refer to a variable whose type is type. o Declarations do not create new objects. Java : Objects & Classes
  • 80.  Creating an Object: o 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"); } } Java : Objects & Classes
  • 81.  Accessing Instance Variables and Methods o Instance variables and methods are accessed via created objects. o The “dot” notation: <object>.<member> o This is used to access object members including attributes and methods. o Examples: d.setWeight(42); d.weight = 42; // only permissible : if weight is public Java : Objects & Classes
  • 82.  Accessing Instance Variables and Methods public class Puppy{ int puppyAge; public Puppy(String name){ // This constructor has one parameter, name. 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"); /* Call class method to set puppy's age */ myPuppy.setAge(2); /* Call another class method to get puppy's age */ myPuppy.getAge(); /* You can access instance variable as follows as well */ System.out.println(myPuppy.puppyA ge ); } } Java : Objects & Classes
  • 83.  Encapsulation: Information hiding o 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 Java : Objects & Classes MyDay  day  month  year
  • 84.  Encapsulation: Information hiding o 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); Java : Objects & Classes MyDay  day  month  year setDay( : Integer) : Void setMonth( : Integer) : Void setYear( : Integer) : Void getDay() : Integer Verify days in month
  • 85.  Encapsulation o Encapsulation is one of the four fundamental OOP concepts. o Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. o If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. o Encapsulation is also referred to as data hiding. Java : Objects & Classes
  • 86.  Encapsulation o Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. o Access to the data and code is tightly controlled by an interface. o Benefits of Encapsulation: o The fields of a class can be made read-only or write-only. o A class can have total control over what is stored in its fields. Encapsulation gives maintainability, flexibility and extensibility to our code. Java : Objects & Classes
  • 87.  Encapsulation Java : Objects & Classes
  • 88.  Source file layout o Basic syntax of a Java source file: [< package_declaration>] [< import_declarations>] < class_declaration>+ o Example, the VehicleReport.java file: package shipping.reports; import shipping.domain.*; import java.util.List; import java.io.*; public class VehicleReport { private List vehicles; public void generateReport() {...} } Java : Objects & Classes
  • 89.  Packages  Packages help manage large software systems.  Packages can contain classes and sub-packages. Java : Objects & Classes
  • 90.  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. Java : Objects & Classes
  • 91.  « 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 Java : Objects & Classes
  • 92.  Directory layout and packages  Packages are stored in the directory tree containing the package name.  Example, the “shipping” application packages: Java : Objects & Classes
  • 93.  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. Java : Objects & Classes

Editor's Notes

  1. This tutorial gives a complete understanding of Java. This reference will take you through simple and practical approach while learning Java Programming language.
  2. 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.
  3. During the creation and execution of a Java program, programs normally go through 5 phases.  These are:
  4. During the creation and execution of a Java program, programs normally go through 5 phases.  These are:
  5. During the creation and execution of a Java program, programs normally go through 5 phases.  These are:
  6. During the creation and execution of a Java program, programs normally go through 5 phases.  These are: