Escolar Documentos
Profissional Documentos
Cultura Documentos
Class Declaration
CLASS Example
class Account
{
private String accountName;
private double accountBalance;
public withdraw();
public deposit();
public determineBalance()
}
OBJECTS
Object-oriented is a way of looking at a Software System as a
collection of interactive objects
Object is an instance of a class
Object represents an entity either physically, conceptual, or
software.
OBJECTS
All the objects share the same attribute names and methods
with other objects of the same class.
Each object has its own value for each of the attribute.
Example of Objects
CLASSES / OBJECTS
OBJECTS
10
ADDING METHODS
A Class with only data fields has no life. Objects created by such a
class cannot respond to any messages.
Methods are declared inside the body of the class but immediately
after the declaration of data fields.
The general form of a method declaration is:
11
Method Declaration
12
13
14
15
16
17
BASIC PRINCIPLES OF OO
Encapsulation
Data Abstraction
OOP
Paradigm
Inheritance
Polymorphism
18
Encapsulation
It associates the code
and
the
data
it
manipulates into a single
unit; and keeps them
Encapsulation
safe
from
external
interference and misuse
OOP
Paradig
m
Data
Abstraction
Inheritance
Polymorphism
19
ENCAPSULATION
All information (attributes and methods) in an object
oriented system are stored within the object/class.
Information can be manipulated through operations
performed on the object/class interface to the class.
Implementation is hidden from the user.
Object support Information Hiding Some attributes and
methods can be hidden from the user
20
ENCAPSULATION - Example
21
Without Encapsulation?
22
With Encapsulation
23
INHERITANCE
New data types (classes) can be defined as
extensions to previously defined type.
Parent Class ( Super Class ) Child Class
Encapsulation
OOP
Paradig
m
( Sub Class)
Subclass inherits properties from the class
Data
Abstraction
Inheritance
Polymorphism
24
INHERITANCE - Example
25
INHERITANCE - Example
26
INHERITANCE - Example
27
ABSTRACTION
Encapsulation
OOP
Parad
igm
Data Abstraction
Inheritance
Polymorphism
28
Polymorphism
Encapsulatio
n
OOP
Paradi
gm
Data
Abstraction
Inheritance
Polymorphis
m
29
30
CONSTRUCTOR
Initializing all the variables in a class is once after the instance is
created.
Automatic initialization is performed through the use of a
constructor.
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is
syntactically similar to a method.
Once defined, the constructor is automatically called immediately
after the object is created, before the new operator completes.
It doesnt have return type, not even void, because of implicit
return type of a class.
Constructor types
Default Constructor
Parameterless Constructor
Parameterized Constructor
31
CONSTRUCTOR
class Account
{
private int id;
private double balance;
id = ac.id;
balance= ac.balance;
constructor
}
}
32
Parameterized Constructor:
Class Box
Class DemoBox
{
{
double width, height, depth;
public static void main(String args[])
//Constructor having arguments
{
Box(double w,double h, double d)
double vol;
{
// Calls Constructor automatically
width = w;
Box b1 = new Box(10,10,10);
height = h;
b1.display();
depth = d;
}
vol = b1.volume();
void display()
System.out.println(Volume is:+vol);
{
}
System.out.println(Width is: + width);
}
System.out.println(Height is: + height);
O/P:
Parameterized Constructor
System.out.println(Depth is: + depth);
Width is:10
}
Height is:10
//Member Function
Depth is:10
double volume()
{
Volume is 1000.0
return width*height*depth;
}
}
34
Copy Constructor
Copying the content of one object to another object by passing the
object to the constructor parameter.
Syntax:
Classname(Classname Obj)
class Box
{
double width;
double height;
double depth;
//Constructor Definition Begins
Box()
{
width = 10;
height = 10;
depth = 10;
}
//Member Function
double volume() {
return width*height*depth;
}
Box(Box b)
{
width=b.width;
height=b.height;
depth=b.depth;
}
}
class ObjectConst
{
public static void main(String args[])
{
double vol;
Box b1 = new Box();
vol = b1.volume();
Box b2 =new Box(b1);
System.out.println("volume "
+b1.volume());
}
}
35
Constructor Overloading
As-like method overloading, constructor can also overloaded.
A class may have more than one constructor definitions, but having
difference in their signature i.e.. Number
of arguments
// constructor
used when cube is
created
class Box
Box(double len)
{
{
width = height = depth = len;
double width, height, depth;
}
// constructor used when all dimensions specified
// compute and return volume
Box(double w, double h, double d)
double volume()
{
{
width = w;
return width * height * depth;
height = h;
}
depth = d;
}
}
// constructor used when no dimensions specified class OverloadCons
{
Box()
public static void main(String
{
args[])
width = -1; // use -1 to indicate
{
height = -1; // an uninitialized
depth = -1; // box
}
36
Constructor Overloading
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
37
Returning Objects
// Returning an object.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Test temp = new Test(a+10); // return new Test(a +10);
return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: + ob2.a);
}
}
Access Modifiers
Controlling the parts of a program that can access by the
members.
By controlling access, we can prevent misuse.-> Black
box, which may be used, but the inner working of which
are not open.
Javas access specifiers are :
40
Access Specifier
41
class Test
class AccessTest
{
{
int a; // default access
public static void main(String args[])
public int b; // public access
{
private int c; // private access
Test ob = new Test();
// These are OK, a and b may be
// methods to access c
void setc(int i) // set c's valueaccessed
directly
{
ob.a = 10;
c = i;
ob.b = 20;
}
int getc() // get c's value
// This is not OK and will cause an
{
error
return c;
// ob.c = 100; // Error!
}
PACKAGES
together.
interfaces
Types of Packages
Java packages are therefore classified into two types.
1. Pre defined packages (Java API Packages)
2. User defined packages
Language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. They include classes for
primitive types, strings, math functions, threads and exceptions
java.util
java.io
Input / Output support classes. They provide facilities for the input and
output of data.
java.awt
java.net
java.apple
t
firstPackage.secondpackage;
Example:
Create Package:
package package1;
public class ClassA
{
public void displayA()
{
System.out.println("Class A");
}
}
How to import the package:
import package1.ClassA;
class PackageTest1
{
public static void main(String args[])
{
ClassA objectA = new ClassA()
objectA.displayA();
}
}
ACCESS
PROTECTION
Access
Modifier
Access
Location
Public
Protected
friendly
(default)
private
Same Class
Yes
Yes
Yes
Yes
Subclass in same
package
Yes
Yes
Yes
No
Other classes in
same
package
Yes
Yes
Yes
No
Subclass in other
package
Yes
Yes
No
No
Non subclasses
in other
packages
Yes
No
No
No
Polymorphism
Polymorphism is the ability of an object to take on many forms. The
most common use of polymorphism in OOP occurs when a parent
class reference is used to refer to a child class object.
The benefit of overriding is: ability to define a behavior that's
specific to the subclass type which means a subclass can
implement a parent class method based on its requirement.
Types:
Static Binding ( Method Overloading)
Dynamic Binding ( Method Overriding)
53
Method Overloading
Method can be overloaded by:
54
Method Overloading
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("a: " + a);
}
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
55
INHERITANCE
Inheritance is a mechanism for extending existing
classes by adding instance variables and methods.
A subclass inherits the methods of its superclass.
The instance variables declared in the superclass are
present in subclass objects.
Any new instance variables that you declare in the
subclass are present only in subclass objects.
A subclass has no access to private instance variables
of its superclass.
A subclass can inherit a superclass method or override
it by providing another implementation.
Use the super reserved word to call a method of the
superclass.
56
INHERITANCE
What is Inheritance?
Inheritance is the mechanism which allows a class B to inherit
properties/characteristics-attributes and methods of a class A. We say B
inherits from A".
A
Example:
A a;
//a is object of A
B b;
//b is object of B
Animal
Horse
Dog
Lion
INHERITANCE
60
Types of Inheritance
1. Single Inheritance (Only one Super Class and One Only Sub Class)
2. Multilevel Inheritance (Derived from a Derived Class)
3. Hierarchical Inheritance (One Super Class, Many Subclasses)
1. Single Inheritance (Only one Super Class and Only one Sub
Class)
C
4. Hierarchical Inheritance (One Super class, Many
Subclasses)
A
63
e Inheritance (Only one Super Class and One Only Sub Class)
//Single Inheritance
class Room
{
protected int length, breadth;
Room()
{
length = 10; breadth = 20;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom()
{
length = 10;
breadth = 20;
height = 30;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length * breadth *
height));
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom hr = new HallRoom();
hr.Room_Area();
hr.HallRoom_Volume();
}
}
//Multilevel Inheritance
class Room
{
protected int length, breadth;
Room()
{
length = 10;
breadth = 20;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom()
{
length = 10; breadth = 20;
height = 30;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length * breadth *
height));
}
}
//Hierarchical Inheritance
class Room
{
protected int length, breadth, height;
Room()
{
length = 10;
breadth = 20;
height = 30;
}
}
class HallRoom extends Room
{
void HallRoom_Area()
{
System.out.println("The Area of the HallRoom is:" + (length *
breadth));
}
}
Method Overriding
1. A subclass can inherit a superclass method or override
it by providing another implementation.
2. Method overriding in java means a subclass method
overriding a super class method.
3. Superclass method should be non-static.
4. Subclass uses extends keyword to extend the super
class.
5. In overriding methods of both subclass and superclass
possess same signatures.
6. Overriding is used in modifying the methods of the
super class.
7. In overriding return types and constructor parameters
71
//Method Overriding
class Room
{
void Room_Super()
{
System.out.println("The Room Base is Displayed");
}
}
class HallRoom extends Room
{
void Room_Super()
{
System.out.println("The Sub Class Room Base is Displayed");
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom br = new HallRoom();
br.Room_Super();
}
}
73
Shadowing
The scope of a variable is the region of a program in which the
variable can be accessed.
Accidentally using the same name for a local variable and an
instance variable is a surprisingly common error.
A local variable can shadow an instance variable with the same
name. You can access the shadowed variable name through the this
reference.
Example
public class Coin
{
private String name;
private double value; // Instance variable
public double getExchangeValue(double exchangeRate)
{
double value; // Local variable with the same name
return value;
}
}
74
this reference
75
76
78
class Room
{
protected int length, breadth, height;
Room(int length, int breadth)
{
this.length = length;
this.breadth = breath;
}
void Room_Area()
{
System.out.println("The Area of the Room is:" + (length * breadth));
}
}
class HallRoom extends Room
{
int height;
HallRoom(int length, int breadth, int height)
{
super(length,breadth); this.height = height;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length *
breadth * height));
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom hr =new HallRoom(10,20,30);
hr.Room_Area();
hr.HallRoom_Volume();
}
}
3. Cant Inherited
final class Super
{
void Super_Method()
{
System.out.println("This is Super Method");
}
}
class Sub extends Super
//cannot inherit from final super
{
void Super_Method()
{
System.out.println("This is Sub Method");
}
}
class Final
{
public static void main(String args[])
{
Sub s = new Sub();
s.Super_Method();
}
}
class UseStatic
{
// Static Data members and Static Member Functions
static int a =3;
static int b;
static void display(int x)
{
System.out.println(A is: +a);
System.out.println(B is:+x);
}
static
{
System.out.println(Static Block Executed First);
}
public static void main(String args[])
{
display(10);
} O/P: Static Block Executed First
}
A is 3
B is 10
90
Instanceof operator
91
Abstract Classes
An abstract class is a class that cannot be instantiated.
An abstract class is a class that contain one or more abstract methods.
A class that declares an abstract method, or that inherits an abstract
method without overriding it, must be declared as abstract.
Also declare classes with no abstract methods as abstract.
92
93
b.callme( );
b.callmetoo( );
}
Interface
1. Java does not support multiple inheritances. That is, classes in java
cannot have more than one superclass. For instances,
class A extends B extends C
{
------------------}
2. Above extends is not permitted in Java. However, the designers of java
could not overlook the importance of multiple inheritances.
3. A large number of real life applications require the use of multiple
inheritances whereby we inherit methods and properties from several distinct
classes.
4. Since C++ like implementation of multiple inheritances proves difficult and
adds complexity to the language, Java provides an alternate approach
known as interfaces to support the concept of multiple inheritances.
5. Although a java class cannot be a subclass of more than one superclass, it
can implement more than one interface, thereby enabling us to create
classes that build upon other classes without the problems created by
Defining Interfaces
An interface is basically a kind of class. Like classes, interfaces contain
methods and variables but with major difference. The difference is that
interfaces define only abstract methods and final fields. This means that
interfaces do not specify any code to implement these methods and data
fields contain only constants.
x:
Syntax:
interface Interface_name
{
Variable declaration;
Method declaration;
}
Ex:
interface Item
{
static final int code = 1001;
static final String name = CCET;
public void display ();
}
interface Area
{
final static float pi = 3.142F;
float compute (float x,float y);
public void show();
}
Abstract classes
Interfaces
all
abstract
members
in
With abstract classes, you are With Interfaces, you are merely
grabbing
extending
away each classs individuality.
each classs functionality.
Types
Interfaces
A
Interfac
e
Interfac
e
Class
Interfac
e
Extension
Implement
s
Class
Interfac
e
Implementatio
n
C
Class
Implementatio
n
Class
Interface
Extension
Implementation
of
Class
Class
Interfac
e
extends
Interfac
e
Implementatio
n
Class
interface A
{
int a=10;
public void disp_A();
}
class B implements A
{
int b=20;
public void disp_A()
{
System.out.println("A's value in Implemented Class: "+ a);
}
public void disp_B()
{
System.out.println("B's value: "+b);
}
}
class C extends B
{
int c;
public void add()
{
c = a+b;
System.out.println("Added value in Derived2 class: "+ c);
}
}
Interfac
e
Implementation
Class
Extension
Class
class Interface2
{
public static void main(String args[])
{
C d = new C();
d.disp_A();
d.disp_B();
d.add();
}
}
Output:
A's value in Implemented Class: 10
B's value: 20
Added value in Derived2 class: 30
interface A
{
int a =10;
public void display_A();
}
interface B extends A
{
int b=20;
public void display_B();
}
class C implements B
{
int c;
public void display_A()
{
System.out.println("A is: "+a);
}
public void display_B()
{
System.out.println("B is: "+b);
}
public void display_add()
{
c = a+b;
System.out.println("Add is: "+ c);
}
}
Interfac
e
Extension
Interfac
e
Implement
s
Class
class MulInterface
{
public static void main(String args[])
{
C derived = new C();
derived.display_A();
derived.display_B();
derived.display_add();
}
}
Output:
A is: 10
B is: 20
Add is: 30
interface A
{
public void display();
Output:
}
Display method in Derived1
class Derived1 implements A
Display method in Derived2
{
public void display()
{
System.out.println("Display method in Derived1");
}
}
class Derived2 implements A
{
public void display()
{
System.out.println("Display method in Derived2");
Interface
}
A
}
class Interface4 {
public static void main(String args[]) {
Derived1 d1 = new Derived1();
Implementatio
n
Derived2 d2 = new Derived2();
d1.display();
d2.display();
B
C
}
}
Class
Class
interface A
{
int a=10;
public void disp_A();
}
interface B
{
int b=20;
public void disp_B();
}
class Derived implements A,B
{
int c;
public void disp_A()
{
System.out.println("A's value is: "+a);
}
public void disp_B()
{
System.out.println("B's value is: "+b);
}
void add()
{
c=a+b;
System.out.println("Added value is: "+c);
}
}
Interfac
e
Implementatio
n
C
Class
class Interface5
{
public static void main(String args[])
{
Derived d = new Derived();
d.disp_A();
d.disp_B();
d.add();
}
}
Output:
A's value is: 10
B's value is: 20
Added value is: 30
interface A
{
int a=10;
public void disp_A();
}
interface B
{
int b=20;
public void disp_B();
}
interface C extends A,B
{
int c=30;
public void disp_C();
}
class Derived implements C
{
public void disp_A()
{
System.out.println("A's value: "+a);
}
Interfac
e
extends
Interfac
e
Implementatio
n
Class
Output:
A's value: 10
B's value: 20
C's value: 30
Add is: 60
Class
A
Interfac
e
Extension
Class
Extension
Class
D
Implementation
Output:
Roll No. 1001
Mark 1: 98
Mark 2: 78
Marks 3: 58
Total
Marks:
234.0
Average: 78.0
Game: Football
Inner Classes:
An inner class is a class that is defined inside another class.
There are three reason to have an inner class:
Inner class methods can access the data from the scope in which
they are defined, including data that would otherwise be private.
Inner classes can be hidden from other classes in the same package.
Anonymous inner classes are handy when you want to define
callbacks without writing a lot of code.
There are several Inner Classes. They are:
Simple Inner Class
Local Inner Class
Anonymous Inner Class
Static Inner Class
1. Simple Inner Class:
. A Simple inner class is a class object which present inside another
class.
. It is present common inside so that it can be accessed by all methods of
the outer class.
. The Outer Class Object can have rights to access its members and the
inner class members along with the inner class object.
class Inner
{
int a;
public void disp_Inner()
{
System.out.println("Inner Class Method");
}
}
class Outer
{
Inner in = new Inner();
int b;
public void disp_Outer()
{
System.out.println("Outer Class Method");
}
}
class InnerOuter
{
public static void main(String args[])
{
int c;
Outer o = new Outer();
o.b = 20;
o.disp_Outer();
o.in.a = 10;
o.in.disp_Inner();
c = o.b + o.in.a;
System.out.println("Added Value: "+c);
}
}
Output:
Outer Class Method
Inner Class Method
Added Value: 30
class LocalInner
{
public static void main(String args[])
{
Outer o = new Outer();
o.disp_Outer();
}
}
Output:
Outer Class Method
Inner Class Method
3. Anonymous Inner Class:
Anonymous classes in Java are more accurately known as
anonymousinnerclasses theres no such thing as anonymous classes
without the inner.
Syntax:
/*Pay attention to the opening curly braces and the fact that
there's a semicolon at the very end, once the anonymous class is
created: */
Anonymous obj = new Anonymous()
{
//code here...
class InnerAnonymous
{
public void display()
{
System.out.println("Normal Class Method");
}
}
class Outer {
/* This creates an anonymous inner class: */
InnerAnonymous n = new InnerAnonymous()
{
public void display()
{
System.out.println("anonymous method in another class");
}
};
void display_outer()
{
n.display();
}
}
class AnonymousClass
{
public static void main(String args[])
{
Outer o = new Outer();
o.display_outer();
//Normal Class object
InnerAnonymous in = new InnerAnonymous() ;
in.display();
}
}
Output:
Anonymous method in another class
Normal Class Method
An anonymous inner class is an inner class that is declared without using a
class name at all and that of course is why its called
ananonymousclass.
Object Class:
TheObject classis the parent class of all the classes in java by
default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose
type you don't know. Notice that parent class reference variable can
refer the child class object, know as upcasting.
Let's take an example, there is getClass() method that returns an
object but it can be of any type like Employee, Student etc., we can use
Object class reference to refer that object. For example:
Syntax:
Object obj = new Student();
obj.getClass();
A variable of type Object is only useful as a generic holder for arbitrary
values.
Method
Description
class Student
{
String name;
int stdid;
Student()
{
name = "Chettinad";
stdid = 1001;
}
void display()
{
System.out.println("Student Name: "+name);
System.out.println("Student ID: "+stdid);
}
}
class ObjectClass
{
public static void main(String args[]) {
Object obj = new Student();
Student e =(Student)obj;
Output:
e.display();
Student Name:
Chettinad
System.out.println(obj.getClass());
Student ID: 1001
System.out.println(obj.hashCode());
class Student
System.out.println(obj.equals(e));
1671711
}
true
}
Enum in java
Enumeration in java supports to use variables that can hold one of a finite
number of values. For example, in the tax return class, the status instance
variable holds one of the values SINGLE or MARRIED.