Você está na página 1de 43

CORE JAVA

Pranav

Why Java?
debug

WRITE ONCE, RUN ANYWHERE!


Program
in Java

Java
Compiler

Java Virtual Machine

Java
Bytecode

pretty
portable

Java Virtual Machine

Introduction to OOP concepts

FOUR MAIN PILLARS OF OBJECT ORIENTED PROGRAMMING LANGUAGES

OOP Concepts
Objects physical or conceptual existence - Building

Classes design or template - Map


Abstraction only relevant info/hiding details ATM slip
Inheritance code reusability and extendibility - Relatives

Polymorphism ability to exist in more than one form

Phone conversation
Encapsulation collection of entities under one unit Tablet

Procedural v/s Object Oriented


Object-Oriented
methods
objects
message
attribute

Procedural
functions
modules
argument
variable

Java Architecture
Java's architecture arises out of four distinct but

interrelated technologies:
Java programming language
Java class file format
Java Application Programming Interface (API)
Java virtual machine (JVM)

Java Architecture (Contd.,)


Relationship between these four parts
JVM and Java API form a "platform" for which all Java programs

are compiled.

javac

java

Java Program Execution

Writing a Classes and Creating Objects


A class is an abstraction of a concept, it encapsulates the state

(member variables) and behavior (methods) of the concept it


represents. Or A Class is a template for an object or class =
data + methods
Object is an instance of a class.

These characteristics represent a pure approach to object-

oriented programming:
1. Everything is an object.
2. A program is a bunch of objects telling each other what to do

by sending messages.
3. All objects of a particular type can receive the same

messages.

Structure of Java class


The components of a class consists:
Data members (Attributes)
Methods
Creating Classes in Java
The statements written in a Java class must end with a

semicolon(;).
class ClassName
{
//Declaration of data members
//Declaration of methods
}

Object
Each object can satisfy only

certain requests.
The

requests you can


make of an object are
defined by its interface.

The type (class) is what

determines the interface.


The

idea of type being


equivalent to interface is
fundamental
in
objectoriented programming.

Light lt = new Light(); // The name of the


type/class is Light
lt.on(); //requests

Object Creation
Box mybox = new Box();

Box mybox; // declare

reference to object
mybox = new Box(); //
allocate a Box object
Box b1 = new Box();
Box b2 = b1;
This is called instance of a

class or instantiating a class

Encapsulation
In java, the basis of encapsulation is class.

It is the mechanism that binds together the code and data.


It keeps both of them safe from outside references and

misuse.
In other words, it brings together all the variables and
methods into a single unit called class.
Objects are instance of a class
The code and data inside the class are members of the
class.
Data is members variables or instance variables, code is
member methods or just methods.
Members can be public, private or protected.

Methods
Class behavior are represented in Java by methods

Method signature methods name and parameter types


The different methods are:

Constructors

1.
a.
b.
c.

Default
Parameterized
Copy

Accessor (Observer) reads the property - getValue()


3. Mutator (transformer) set the property values setValue()
4. Helper useful inside the class but not outside the class
5. Recursive
2.

Constructor
To initialize the object

Same name as the class name


No return type, if so then not a constructor then its a method.
If there is no constructor, then compiler inserts one.

If you define any constructors, the compiler will not insert one.
A class can have more than one constructor.
When we create an object, constructor is executed.
Example:
Class A {
A() { //constructor
//Statements
}
}

A a1= new A();

Inheritance
IS A relationship

Code reusability and code extendibility


In java keyword extends is used to inherit
The class by which you inherit is called super

or parent class and the derived or inherited is


called child class or subclass
Example: class B extends A
In OOAD we represent
class
subclass-name
extends
superclass- name {
//body of class
}

Polymorphism
Polymorphism means many forms in Greek language

It is a feature that allows one interface to be used for a

general class of actions.


Polymorphism is expressed by phrase one interface,
multiple methods.
Static Binding
Works at compile time
Function overloading is static binding

Dynamic Binding
Works at runtime
A particular object acts differently depending on the type references
passed to it

Overloading Methods
In Java, it is possible to define two or more methods

within the same class and share the same name as long
as their parameter declarations are different.
The methods are said to be overloaded, and the process
is referred to as method overloading
//Method overloading
public class MethodOverloadingDemo {
void method(){
System.out.println("First way with no parameters");
}
void method(int x){
System.out.println("Second way with one parameter "+x);
}

Overloading v/s Overriding


Overloading deals with multiple methods with the same

name in the same class, but with different signatures


Overriding deals with two methods, one in a parent class

and one in a child class, that have the same signature


Overloading lets you define a similar operation in different

ways for different data


Overriding lets you define a similar operation in different

ways for different object types

Abstract Classes
Often in a design, you want the base class to present only an

interface for its derived classes.


This is accomplished by making that class abstract using the abstract

keyword.
You can also use the abstract keyword to describe a method that

hasnt been implemented yet as a stub indicating here is an


interface function for all types inherited from this class, but at this
point I dont have any implementation for it.
An abstract method may be created only inside an abstract class.

When the class is inherited, that method must be implemented, or the


inherited class becomes abstract as well.
Creating an abstract method allows you to put a method in an

interface without being forced to provide a possibly meaningless body


of code for that method.

When to use Abstract Classes


Any smaller phone to bigger phone model uses the

procedure like messaging, call records, games etc.,


The s/w part is same for the old small mobile to new
advanced mobile the operations are same
What we had planned to should work for all

Interface
An interface is a set of methods & constants that

are identified with a name.


These are similar to Abstract classes
You cannot instantiate interfaces
An interface introduces types

They are completely abstract (no implementation)

100% abstraction
Class & abstract classes realize or implement
interfaces
They must have (atleast) all the methods and constants

of the interface with public visibility

Why Use Interface?


To separate (decouple) the specifications available to the

user from implementation


We can use any class that implements interface through
the interface type (polymorphism)
As a partial solution, Javas lack of multiple inheritance

When to use Interfaces


Most of the industry projects will have a contract at the

time of signing
It is agreed upon what to implement for what?
A bank application is designed in such a way that it has to
work on computer and also on mobile devices
At that situation the projects are implemented for both
Now a sort of contract is set-up such that all the computer
based programs are designed to be executed as heavy
process and all mobile platforms programs are designed
to be executed as light weight process

Abstract classes v/s Interface


Abstract Classes

Interface

Can have data fields

Can only have a constant

Methods may have an


implementation

Methods have no implementation


100% abstraction

Class and Abstract classes extend


abstract class

Classes and Abstract classes


implement interface

Class cannot extend multiple


abstract class

Interface can extend multiple


interfaces

Substitution principle is assumed

Substitution principle not assumed

A class can extend an abstract


class

A class can implement interface

Java Access Specifier


The first data column indicates whether the class itself has access to

the member defined by the access level.


As you can see, a class always has access to its own members.
The second column indicates whether classes in the same package

as the class (regardless of their parentage) have access to the


member.
The third column indicates whether subclasses of the class which are

declared outside this package can have access to the member.


The fourth column indicates whether all classes have access to the

member.

Access Levels
Modifier

Class Package Subclass World

public

protected

no modifier

private

Strings
In Java a string is a sequence of characters. But, unlike

many other languages that implement strings as character


arrays, Java implements strings as objects of type String.
For those cases in which a modifiable string is desired,
there is a companion class to String called StringBuffer.
Both the String and StringBuffer classes are defined in
java.lang.
To create an empty String, we call the default constructor.

For example: String s = new String(); will create

an instance of String with no characters in it.

Mutable and Immutable Objects


Mutable object
If an object value is changeable then we can call it as Mutable object.
Cant use + for adding two strings
new operator is must to create mutable object
Ex., StringBuffer, StringBuilder

Immutable Objects
If you are not allowed to change the value of an object, it is immutable
object.
Can use + for adding two strings
new operator is not mandatory to create immutable object
Ex., String, Integer, Float,
The string object is immutable, but the reference variable is

not.

StringBuffer
StringBuffer is a peer class of String that provides much

of the functionality of strings.


As you know, String represents fixed-length, immutable
character sequences.
No concat, use append
It has synchronized methods, jdk1.0 onwards.
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
System.out.println("charAt = " + sb.charAt(2));
}
}

StringBuffer & StringBulider


Objects of type StringBuffer and StringBuilder can be

modified over and over again without leaving behind


discarded String objects
The StringBuilder class was added in Java 5
It has exactly the same API as the StringBuffer class,
except StringBuilder is not thread safe i.e. its methods are
not synchronised
Sun recommends that you use StringBuilder instead of
StringBuffer whenever possible because StringBuilder will
run faster
There is no major difference in the methods of the two
classes

Exception Handling
If a runtime error has occurred the FOC abruptly stops

execution. What if we want to continue further execution?


An Exception is an abnormal condition that arises in a

code sequence at run time.


A Java Exception is an object that describes an

exceptional condition that has occurred.


Exceptions can be generated and thrown automatically by

the Java-Runtime system or your code.


Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.

Keywords: try, catch, throw, throws, finally


Program statements lead to exceptions are put within a

try block.
If an exception occurs within the try block, it is thrown, so
code can catch this exception (using catch)
To throw a specific exception from the program, use the
keyword throw.
Specifies which exception a given method can throw by a
throws clause. (duck)
Any code that absolutely must be executed (whether or
not exception has occurred) before a method returns is
put in a finally block.
Any user-defined exception class is a subclass of the
exception class

Multiple catch

In some cases, more than one exception could be raised by a

single piece of code.


To handle this type of situation, you can specify two or more
catch clauses, each catching a different type of exception.
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
a=0
System.out.println("a = " + a);
Divide by 0:
int b = 42 / a;
java.lang.ArithmeticExceptio
int c[] = { 1 };
n: / by zero
c[42] = 99;
}
After try/catch blocks.
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
e.printStackTrace();
}
System.out.println("After try/catch blocks.");
}
}

Nested try
The try statement can be nested. That is, a try statement

can be inside the block of another try.


// An example of nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
int b = 42 / a; // If no command-line args
System.out.println("a = " + a);
try { // nested try block
if(a==1) a = a/(a-a);//1 cmd-line arg
if(a==2) {//generate an out-of-bound exc
int c[] = { 1 };
c[42] = 99;
}
}

throw & throws


One declares it, and the other one does it
Throw is used to actually throw the exception, whereas throws is

declarative for the method. They are not interchangeable.


public void myMethod(int param) throws MyException {
if (param < 10) {
throw new MyException("Too low!);
}
//Blah, Blah, Blah...
}
The Throw clause can be used in any part of code where you feel a
specific exception needs to be thrown to the calling method.
If a method is throwing an exception, it should either be surrounded
by a try catch block to catch it or that method should have the throws
clause in its signature.
Without the throws clause in the signature the Java compiler does not
know what to do with the exception.
The throws clause tells the compiler that this particular exception
would be handled by the calling method.

finally
finally creates a block of code that will be executed after

a try/catch block has completed and before the code


following the try/catch block.
The finally block will execute whether or not an exception
is thrown.
If an exception is thrown, the finally block will execute
even if no catch statement matches the exception.

Serialization
Serialization is the process of writing the state of an object

to a byte stream.
This is useful when you want to save the state of your
program to a persistent storage area, such as a file. At a
later time, you may restore these objects by using the
process of deserialization.
Serialization is also needed to implement Remote Method
Invocation (RMI).
RMI allows a Java object on one machine to invoke a
method of a Java object on a different machine.
The sending machine serializes the object and transmits
it.
The receiving machine deserializes it.

Serialization scenario
Assume that an object to be serialized has references to other

objects, which, in turn, have references to still more objects.


This set of objects and the relationships among them form a
directed graph. There may also be circular references within
this object graph.
That is, object X may contain a reference to object Y, and
object Y may contain a reference back to object X.
Objects may also contain references to themselves.
The object serialization and deserialization facilities have been
designed to work correctly in these scenarios.
If you attempt to serialize an object at the top of an object
graph, all of the other referenced objects are recursively
located and serialized.
Similarly, during the process of deserialization, all of these
objects and their references are correctly restored.

Serializable
Only an object that implements the Serializable interface

can be saved and restored by the serialization facilities.


If a class is serializable, all of its subclasses are also
serializable.
Variables that are declared as transient are not saved by
the serialization facilities. Also, static variables are not
saved.

Transient and Volatile modifiers


Java defines two interesting type modifiers: transient and

volatile. These modifiers are used to handle somewhat


specialized situations.
When an instance variable is declared as transient, then its
value need not persist when an object is stored. For example:
class T {
transient int a; // will not persist
int b; // will persist
}

Here, if an object of type T is written to a persistent storage

area, the contents of a will not be saved, but the contents of b


will be saved.
The volatile modifier tells the compiler that the variable
modified by volatile can be changed unexpectedly by other
parts of your program.

Externalizable
The Java facilities for serialization and deserialization have

been designed so that much of the work to save and restore


the state of an object occurs automatically.
However, there are cases in which the programmer may need
to have control over these processes. For example, it may be
desirable to use compression or encryption techniques.
The Externalizable interface is designed for these situations.
The Externalizable interface defines these two methods:
void readExternal(ObjectInput inStream) throws IOException,
ClassNotFoundException
void writeExternal(ObjectOutput outStream) throws
IOException
In these methods, inStream is the byte stream from which the
object is to be read, and outStream is the byte stream to which
the object is to be written.

Benefits of Serialization
The streaming interface to I/O in Java provides a clean

abstraction for a complex and often cumbersome task.


The stream classes allows you to dynamically build the
custom streaming interface to suit your data transfer
requirements.
Java programs written to adhere to the abstract, highlevel InputStream, OutputStream, Reader, and Writer
classes will function properly in the future even.
Finally, serialization of objects is expected to play an
increasingly important role in Java programming in the
future.
Javas serialization I/O classes provide a portable solution
to this sometimes tricky task.

Wrappers
These are classes that encapsulate a primitive data type

within an object
There are plenty of wrapper classes
Example:
Character is a wrapper around char. To obtain a char
value in a Character object, use char charValue();
Boolean is a wrapper around boolean. To obtain a
boolean value of a Boolean object, use boolean
booleanValue()
Integer, Long, Float etc., for numerical

Você também pode gostar