0% found this document useful (0 votes)
6 views64 pages

Object Oriented Features in Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views64 pages

Object Oriented Features in Java

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Object-oriented programming

with JAVA

Presented By: Ms. Karuna


Assistant Professor
Department of Information
Technology
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
abstract other identifier
assert boolean break
names. byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implemen
ts
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchroni this throw
zed
throws transient try void
volatile while
Java: Datatypes
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
My First program in Java

public class Hello {


public static void main(String args[]) {
[Link]("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 [Link]() 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


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 A variable that is
A variable that is
declared inside the class declared as static is
declared inside the
method is called local but outside the method called static (also
variable. is called instance class) variable. It
variable . It is not cannot be local.
declared as static.
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 public class Test{
o Example: public void myAge(){
public class Test{ int age ;
public void myAge(){ age = age + 7;
int age = 0; [Link](“My age is : " +
age = age + 7; age);
[Link](“My age is : " + }
age); public static void main(String args[])
} { Test test = new Test();
public static void main(String args[]) [Link](); }
{ Test test = new Test(); }
[Link](); } [Link][Link]variable number might not
} have been initialized
age = age + 7;
My age is: 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


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 . [Link].
Java: Variables
Instance variables
 Example:
// This method prints the employee details.
public class Employee{ public void printEmp(){
// this instance variable is visible for any [Link]("name : " +
child class.
name );
public String name;
[Link]("salary :" +
// salary variable is visible in Employee salary); }
class only.
public static void main(String args[]){
private double salary;
Employee empOne = new
// The name variable is assigned in the
Employee("Ransika");
constructor.
[Link](1000);
public Employee (String n){
[Link]();
name = n; }
// The salary variable is assigned a value. }}
public void setSalary(double s){ 
salary = s; } salary :1000.0
name : Ransika
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 [Link].
 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;
[Link](DEPARTMENT+"average salary:"+salary);
}}

 Development average salary:1000

Note: If the variables are access from an outside class


the constant should be accessed as
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.
Operato Description
r
+ 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
Java : Operators
 Relational Operators:
There are following relational operators
supported by Java language
Operat Description
or
== Checks if the values of two operands are equal or not, if yes then
condition becomes true.
!= Checks if the values of two operands are equal or not, if values
are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value of
right operand, if yes then condition becomes true.
< Checks if the value of left operand is less than the value of right
operand, if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the
value of right operand, if yes then condition becomes true.
<= Checks if the value of left operand is less than or equal to the
value of right operand, if yes then condition becomes true.
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

Java : Operators
Logical Operators:

Operat Description
or
&& 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:

Operato Description
r
= 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
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).
Objec Individual

A class is a
t1 objects are

software design
Objec created from
the class design
which describes t2 for each actual
the general Objec thing.
properties and class
bihaviours of
t3
something Objec
t4

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)
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:
Access Keyword Name of the
modifier class class

Pubic class MyClass


{
Class body: variables, methods
NO semi-colon
}
Java : Objects & Classes
Class
o Example:

public class Dog{


String breed;
int age; variables
String color;
void barking(){ }
void hungry(){ } methods
void sleeping(){ }

}
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.
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 [Link]
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
Methods

o Anatomy of a Method:
Access Return Name of the
Parameters
modifier type method

public double getSalary

(String name)
Method code: local variables and
{
statements

}
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
 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


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:
[Link](42);
[Link] = 42; // only permissible : if weight is public
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.

}
Java : Objects & Classes
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 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
Inheritence in Java
Inheritance in Java is a mechanism in
which one object acquires all the properties
and behaviors of a parent object. It is an
important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that


you can create new classes that are built
upon existing classes. When you inherit
from an existing class, you can reuse
methods and fields of the parent class.
Moreover, you can add new methods and
fields in your current class also.
Inheritence in Java
 Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

Terms used in Inheritance


 Class: A class is a group of objects which have common properties. It
is a template or blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other
class. It is also called a derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent
class.
 Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class
when you create a new class. You can use the same fields and
methods already defined in the previous class.
Java: Types of Inheritence
Java: Types of Inheritence
JAVA: Interface
Like a class, an interface can have methods and
variables, but the methods declared in an
interface are by default abstract (only method
signature, no body).

Interfaces specify what a class must do and not


how. It is the blueprint of the class.

If a class implements an interface and does not


provide method bodies for all functions
specified in the interface, then the class must
be declared abstract.
JAVA: Interface
Why do we use interface ?

It is used to achieve total abstraction.


Since java does not support multiple
inheritance in case of class, but by using
interface it can achieve multiple inheritance .
It is also used to achieve loose coupling.
JAVA: Interface
Relationship between Class and
Interface:
Class:Interface
Class:Interface
Class:Interface
Difference between class and
Interface
JAVA: Abstraction
Abstraction is a process of hiding the
implementation details and showing only
functionality to the user. Another way, it
shows only essential things to the user and
hides the internal details, for example,
sending SMS where you type the text and
send the message. You don't know the
internal processing about the message
delivery.
Abstraction lets you focus on what the
object does instead of how it does it.
For implementing Abstraction we can use
 Abstract Class
JAVA: Abstraction
 Abstract class in Java
 A class which is declared as abstract is known as an abstract
class. It can have abstract and non-abstract methods. It
needs to be extended and its method implemented. It cannot
be instantiated.

 Points to Remember

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to
change the body of the method.
JAVA: Abstraction
Interface vs. Abstract Class

You might also like