Nothing Special   »   [go: up one dir, main page]

OOP in Java Slide

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

Programming paradigms

• Procedural/Structural Programming
– Conventional programming using high level languages such as COBOL,
Fortran, Pascal and C
– Problem is viewed as a sequence of things to be done such as Input—
Process---Output
– A number of functions are written to accomplish these tasks

– The primary focus is on functions

– Functions transform data from one form to another

– While concentrating on the development of functions ,very little attention is


given to the data that are being used by various functions
– Global data are more vulnerable to an inadvertent change by a function

– In large program it is very difficult to identify what data is used by which


function.
Programming paradigms
• Object Oriented Programming
– Emphasis is on data rather than procedures

– Programs are defined in to what are known us objects.

– Data structures are designed such that they characterize the object

– Functions that operate in the data of an object are tied together in


the data structure

– Data is hidden and can’t be accessed by external functions

– Objects may communicate with each other through functions

– New data and functions can be easily added whenever necessary.

– Follows bottom-up approach in program design


Features of OOP
• Object
– Are the basic runtime entities in OO system and they may represent a person,
thing, event, concept, screen or report, place, a bank account, or any
Information.
– When program is executed the object interact by sending messages to one
another
– Object can interact without having to know details of each others’ data or code

• Class
– Generalizes/ represents a collection of similar objects and is effectively a
template from which to create objects
– Definition of data and code for creating objects

– Once a class has been defined we can create any number of Objects belonging
to that class
Features of OOP

• Abstraction
– Process of Identifying the relevant qualities and behaviors an object
should possess
– Is a process that involves identifying the critical behavior of an object
and eliminating irrelevant and complex details.

• Encapsulation
– The wrapping up of data and functions in to a single unit called class.

– Data is not accessible to the outside world and only those functions
which are wrapped in the class can access it.
– This insulation of data from direct access by the program is called
Data/Information hiding.
Features of OOP

• Inheritance
– Is the process by which object of one class acquires the properties of an
other class.
– It supports the concept of hierarchical classification

– Provides the idea of reusability that is we can add additional features to an


existing class without modifying it.
– It is possible by deriving a new class will have the combined features of
both the classes.

• Polymorphism
– Ability to make more than one form

– An operation may exhibit different behaviors in different instances

– The behavior depends upon the type of data and number of arguments
Features of Java
• Simple
– Java inherits the C/C++ syntax and many of the object-oriented features of C++,
most programmers have little trouble learning Java
– To write and more readable and eye catching

– In Java, there are a small number of clearly defined ways to accomplish a given task

– Pointers are not available in java

• Secure
– Can’t harm Other system

– Secure means of creating internet applications

– When you use a Java-compatible Web browser, you can safely download Java
applets without fear of viral infection or malicious intent.
– Java achieves this protection by confining a Java program to the Java execution
environment and not allowing it access to other parts of the computer
– Enables the construction of various free and tamper free system
Features of Java

• Portable

– Many types of computers and operating systems are in use throughout

the world—and many are connected to the Internet. For programs to be

dynamically downloaded to all the various types of platforms

connected to the Internet, some means of generating portable

executable code is needed-byte code

– Same result on all machines

– Can execute in any environment for which there is JVM

• Object Oriented

– The object model in Java is simple and easy to extend, while simple

types, such as integers, are kept as high-performance non objects.


Features of Java

• Multithreaded

– The Java run-time system comes with an elegant yet sophisticated solution

for multi process synchronization that enables you to construct smoothly

running interactive systems.

• Robust

– Knowing that what you have written will behave in a predictable way

under diverse conditions is a key feature of Java. To better understand how

Java is robust, consider two of the main reasons for program failure:

memory management mistakes and mishandled exceptional conditions

(that is, run-time errors).

– Encourages error free programming by being strictly typed and performing


Features of Java

• Architecture neutral
– One of the main problems facing programmers is that no guarantee
exists that if you write a program today, it will run tomorrow—even
on the same machine. Operating system upgrades, processor
upgrades, and changes in core system resources can all combine to
make a program malfunction. The Java designers made several hard
decisions in the Java language and the Java Virtual Machine in an
attempt to alter this situation. Their goal was “write once; run
anywhere, any time, forever.”
Features of Java

• Interpreted and High performance


– Java enables the creation of cross-platform programs by compiling
into an intermediate representation called Java byte code. This code
can be interpreted on any system that provides a Java Virtual
Machine. while it is true that Java was engineered for interpretation,
the Java byte code was carefully designed so that it would be easy to
translate directly into native machine code for very high
performance by using a just-in-time compiler.
Features of Java
• Distributed
– Java is designed for the distributed environment of the Internet,
because it handles TCP/IP protocols. In fact, accessing a resource
using a URL is not much different from accessing a file. This allowed
objects on two different computers to execute procedures remotely.
– Java revived these interfaces in a package called Remote Method
Invocation (RMI). This feature brings an unparalleled level of abstraction to
client/ server programming.
– Can be transmit, and run over internet
Features of Java

• Dynamic
– Java programs carry with them substantial amounts of run-time type
information that is used to verify and resolve accesses to objects at
run time. This makes it possible to dynamically link code in a safe
and convenient manner.
– This is crucial to the robustness of the applet environment, in which
small fragments of byte code may be dynamically updated on a
running system
Architecture of JVM
Architecture of JVM
• Java is developed with the concept of WORA (Write Once
Run Anywhere).

• JVM is divided in to three main subsystems:

1. Class Loader Subsystem


It performs three major functionalities: Loading, Linking and Initialization

2. Runtime Data Area


Method area, Heap area, Stack area, PC registers and Native method stack

3. Execution Engine
Interpreter, JIT, GC, JNI and Java Method Libraries
Basics in Java Programming

• Structure of java Program


– [Documentation] --------- suggested
– [package statement] ------ optional
– [import statements] ------ optional
– [interface statements] ------ optional
– [class definitions] ------ optional
– [main-method class] ------ Essential
Basics in Java Programming
• Creating, Compiling and Running a Java Program

– Create a source file and write in the Java program.

– Compile the source file into a byte code file using the compiler, javac

– Run the program contained in the byte code file using The Java interpreter

installed on your computer.

– The file name should be the same as the name of the class containing our main-

method

– A program can contain one or more class definitions but only one public class

definition. This class is called main-class because it contains the main method.

– The program can be created in any text editor

– If a file contains multiple classes, the file name must be the class name of the class

that contains the main method


Basics in Java Programming
• Creating, Compiling and Running a Java Program
public class MyFirstJavaProgram {

public static void main(String []args) {


System.out.println("Hello World");
}
}

– System and String classes are directly used, because they are found in the

package java.lang in which it is automatically included in any java program.

– public (access modifier) makes the item visible from outside the class. static

indicates that the main() method is a class method not an instant method. It

allows main() to be called without having to instantiate a particular instance

of the class.
Basics in Java Programming
• Java Tokens
– Tokens are meaningful words and symbols used by a programming language. They are the
smaller individual units inside a program the compiler recognizes when building up the
program.
– There are five types of Tokens in Java: Reserved keywords, Identifiers, Literals, operators,
separators. abstract Float public
• Reserved keywords boolean For return
Break If short
Byte Implements static
• These reserved words are Case Import super
words with special catch Instanceof switch
Char Int synchronized
meaning to the compiler.
class Interface this
• They could not be used as continue Long throw

constant or variable or any default Native throws


Do New transient
other variable/identifier
double Null try
names. Else Operator void
extends Package volatile
final Private while
finally Protected
Basics in Java Programming
• Identifiers
– Identifiers are programmer defined tokens.
– They include names used to identify classes, methods, variables, objects, packages, and
interfaces.
– Java programming language is case sensitive language

– The name must begin with Letters or _ or $

– Remaining characters of the name of identifiers could be : Letters or Digits

– Example of valid names: age, $salary, _value, _1_value

– Example of illegal identifiers: 123abc, -salary

– Class names: starts with capital letter and should be inter-capital

– Variable names: start with lower case and should be inter-capital

– Method names: start with lower case and should be inter-capital

– Constants: often written in all capital and use underscore if you are using more than

one word.
Basics in Java Programming
• Literals

– Literals are values to be stored in variables. They are a sequence of

characters (digits, letters, & other characters) .


• Operators

– Operators are a symbol that take one or more arguments (operands) and operates

on them to produce a result. Eg. +, *, -, /, %...

– In general, there are 8-kinds of operators:

Categories of operators are as follows:


1. Arithmetic operators

2. Logical operators

3. Relational operators

4. Assignment operators

5. Conditional operators

6. Increment and decrement operators

7. Bit wise operators

8. Special operators
Basics in Java Programming

• Separators
– Separators are symbols used to indicate where groups of codes are
divided and arranged. They define the shape and function of our code.
Some of them are: Parenthesis ( ), braces { }, brackets [ ], semicolon ;,
comma,, period .

• Java Comments
– Java allows putting our comments for making clarifications to our java
codes. The compiler skips comments during compiling. These comments
can be written using three ways.
Start End Purpose

/* */ The enclosed text is treated as a comment.

// (none) The rest of the line is treated as a comment.

/** */ The enclosed text is treated as a comment by the compiler but is used by JavaDoc
to automatically generate documentation.
Basics in Java Programming
• White space
– Java white spaces include: space, tab, newline.
• Java Statements
– Statements are roughly equivalent to sentences in natural languages. A
statement is terminated using a semi colon. It forms a complete unit of
execution. Java statements are categorized as follows

Java statements

Labeled Control Synchronization Guarding


statement statement statement statement

Selection Iteration/loop
Jump statement
statement statement

If( ) While( ) break

If( )… else do…while() continue

Switch( ) for( ) return


Constructors
• Special type of method used to initialize the object.
• Invoked at the time of object creation.
• It constructs the values i.e. provides data for the object that is
why it is known as constructor.
• If there is no constructor in a class compiler automatically creates a default
constructor
Rules for creating java Constructor
– Constructor name must be same as its class name
– Constructor must have no explicit return type even void
– Constructor can’t be abstract, final ,native, static or synchronized
Types of java Constructor
– Default constructor or no-arg constructor
– Parameterized constructor
– Copy constructors
Using the this keyword
• With in an instance method or a constructor, this is a reference
to the current object- the object whose method or constructor
is being called.
• You can refer to any member of the current object from within
an instance method or a constructor by using this.
Inheritance
• mechanism in which one object acquires all the properties and behaviors of parent
object.
• classes can be derived from other classes, thereby inheriting fields and methods from
those classes. Definitions: A class that is derived from another class is called a subclass
(also a derived class, extended class, or child class)
• Is use for Method and for Code Reusability.
• represents the IS-A relationship, also known as parent-child relationship.
• Syntax:
class Subclass-name extends Super class-name {
//methods and fields
}
• Constructors are not members of classes and only members are inherited. You cannot
inherit a constructor. That is, you cannot create a instance of a subclass using a
constructor of one of it's super classes. A constructor may only be called with new .
• Type of Inheritance
– Single inheritance
– Multiple inheritance
– Hierarchical inheritance
– Hybrid inheritance
– Multilevel Inheritance
Inheritance Cont…
• Access modifiers
• Java provides a number of access modifiers to set access levels
for classes, variables, methods and constructors
– private: Visible to the class only
– protected: Visible to the package and all subclasses
– public: Visible to the world
– package: Visible to the package. the default. No modifiers are needed.
The following rules for inherited methods are enforced:
– Methods declared public in a super class also must be public in all subclasses.
– Methods declared protected in a super class must either be protected or public
in subclasses; they cannot be private.
– Methods declared without access control (no modifier was used) can be declared
more private in subclasses.
– Methods declared private are not inherited at all, so there is no rule for them.
Abstract Classes
• Abstract classes may or may not contain abstract methods ie., methods
with out body ( public void get(); )
• But, if a class have at least one abstract method, then the class must be
declared abstract.
• If a class is declared abstract it cannot be instantiated.
• To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.
• If you inherit an abstract class you have to provide implementations to all
the abstract methods in it.
• Abstract Method
– abstract keyword is used to declare the method as abstract.
– You have to place the abstract keyword before the method name in the method
declaration.
– An abstract method contains a method signature, but no method body.
– Instead of curly braces an abstract method will have a semi colon ( ; ) at the end.
Abstract Class cont…
• Declaring a method as abstract has two consequences:
– The class containing it must be declared as abstract.
– Any class inheriting the current class must either override the abstract
method or declare itself as abstract.
Interface
• Collection of abstract methods
• A class implements an interface, thereby inheriting the abstract methods of
the interface.
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear
in an interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
• An interface is implicitly abstract. You do not need to use the abstract
keyword while declaring an interface.
• Each method in an interface is also implicitly abstract, so the abstract
keyword is not needed
• .Methods in an interface are implicitly public.
Polymorphism
• Ability of an object to take on many forms.
• Parent class reference is used to refer to a child class object.
• It is a feature that allows one interface to be used for a general
class of actions.
• An operation may exhibit different behavior in different
instances.
• The behavior depends on the types of data used in the
operation.
• It plays an important role in allowing objects having different
internal structures to share the same external interface.
• Polymorphism is extensively used in implementing inheritance.
• Virtual method is a function or method whose behavior can be
overridden within an inheriting class by a function with the same
signature.
Method overloading
• Overloading can take place in the same class or in its
sub-class.
• Constructor in Java can be overloaded
• Overloaded methods must have a different argument
list.
• Overloaded method should always be the part of the
same class (can also take place in sub class), with same
name but different parameters.
• The parameters may differ in their type or number, or in
both.
• They may have the same or different return types.
• It is also known as compile time polymorphism.
Method Overriding
• applies only to inherited methods
• object type (NOT reference variable type) determines
which overridden method will be used at runtime
• Overriding method can have different return type
(refer this)
• Overriding method must not have more restrictive
access modifier
• Abstract methods must be overridden
• Static and final methods cannot be overridden
• Constructors cannot be overridden
• It is also known as Runtime polymorphism.

You might also like