Você está na página 1de 124

CLASS

A Class represents a template for several objects that


have common properties
A class defines all the properties common to the object
attributes and methods.
A Class is a set of attributes and operations that are
performed on the attributes.
A Class is the blueprint from which individual objects are
created.
An object is an instance of a class

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

What goes inside a class

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:

type methodName (Paramter-list)


{
method-body;
}

11

Method Declaration

12

ADDING METHODS TO CLASS CIRCLE

13

CREATING OBJECTS OF A CLASS

14

CREATING OBJECTS OF A CLASS

15

Accessing Object Data

16

EXECUTING METHODS ON OBJECT

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

Abstraction refers to the act of


representing
essential
features
without including the background
details or explanations. Classes use
the concept of abstraction and are
defined as a list of abstract
attributes such as size, weight and
cost, and methods that operate on
these attributes.

Polymorphism

28

Polymorphism
Encapsulatio
n
OOP
Paradi
gm

Data
Abstraction
Inheritance

An Object of type circle or


rectangle can be assigned to a
Shape object. The behavior of the
object will depend on the object
passed.

Polymorphis
m

29

POLYMORPHISM Method Overloading

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;

Initialize state of the object


Special method have same
name as that of class name
Default
constructor
Cant return anything
public Account()
{}
Doesnt have return type
public Account( int a, double
Can only be called once for an
b)
object
{
Parameterized
Can be private
constructor
id = a;
Cant be static
balance = b;
Can overloaded but cant
}
overridden
public Account( Account ac)
Can be
Copy
{
Default, parameterized, and
Copy constructor

id = ac.id;
balance= ac.balance;

constructor

}
}
32

Default Constructor Example


Class Box
Class DemoBox
{
{
double width;
public static void main(String
args[])
double height;
{
double depth;
double vol;
//Constructor Definition Begins
// Calls Constructor automatically
Box()
Box b1 = new Box();
{
vol = b1.volume();
width = 10;
System.out.println(Volume is:+vol);
height = 10;
}
depth = 10;
}
}
O/P:
Volume is 1000.0
//Member Function
double volume()
{
return width*height*depth;
}
}
33

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
}

// create boxes using the various


constructors

Box mybox1 = new Box(10, 20,


15);

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

Using Objects as Parameters


class Test
{
int a, b;
Test(int i, int j)
{
a = i; b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o)
{
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb
{
public static void main(String args[])
{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
} }

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

// You must access c through its


methods
ob.setc(100); // OK
System.out.println("a, b, and c:
+
ob.a + " " + ob.b + " " +
ob.getc());
}

Packages are javas way of grouping a variety of classes and / or

PACKAGES
together.

interfaces

The grouping is usually done according to

functionality. In fact, packages act as containers for classes. What


are the benefits of Packages?
What are the benefits of Package?
The classes contained in the packages can be easily reused.
In packages, classes can be unique compared with classes in other
packages. That is, two classes in two different packages can have
the same name. They may be referred by their fully qualified name,
comprising the package name and class name.
Package provide a way to hide classes thus preventing other
programs or package from accessing classes that are meant for
internal use only.
Packages also provide a way for separating design from coding.
First we can design classes and decide their relationships, and then we
can

implement the java code needed for the methods. It is possible

Types of Packages
Java packages are therefore classified into two types.
1. Pre defined packages (Java API Packages)
2. User defined packages

1.Java API Packages


Package Contents
Name
java.lang

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

Language utility classes such as vectors, hash tables, random numbers,


date,etc.

java.io

Input / Output support classes. They provide facilities for the input and
output of data.

java.awt

Set of classes for implementing graphical user interface. They include


classes for windows, buttons, lists, menus and so on.

java.net

Classes for networking. They include classes for communicating with


local computers as well as with internet servers.

java.apple
t

Classes for creating and implementing applets.

2. USER DEFINED PACKAGES


How to Creating our own Packages
Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form
package package_name;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are
stored.
4. Save the Package file in .java compile the file creates .class file in the
subdirectory.
5. The subdirectory name must match the package name exactly.
Note:
Java also supports the concept of package hierarchy. This done by
specifying multiple names in a package statement, separated by dots.
Example:
package

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

Example program for the above Access Protection Tabular


Protection.java:
package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

This is file Derived.java:


package p1;
public class Derived_Prot extends Protection
{
public Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
//System.out.println("n_pri = " + n_pri); //Cannot Access because
//accessing level is same class
//in same package
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

This is file SamePackage.java:


package p1;
public class SamePackage
{
public SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
//System.out.println("n_pri = " + p.n_pri); //Cannot Access because
//accessing level is same
//class in same package
System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

This is file OtherPackage.java:


package p1.p2;
public class Protection2 extends p1.Protection
{
public Protection2()
{
System.out.println("derived other package constructor");
// System.out.println("n = " + n);
//Cannot Access because
//accessing level is non sub
//class same class
// System.out.println("n_pri = " + n_pri); //Cannot Access because
//accessing level is same
//class in same package
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}

This is file OtherPackage.java:


package p1.p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// System.out.println("n = " + p.n);
// Cannot access because the
// accessing level is non sub
//
class in same package
// System.out.println("n_pri = " + p.n_pri);// Cannot access
// because the accessing
// level is
same class in
// same package
// System.out.println("n_pro = " + p.n_pro);
// Cannot access
// because the accessing
// level
is sub class in
// other package
System.out.println("n_pub = " + p.n_pub);
}
}

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:

By Varying the type of the parameter

By Varying the order and position of the


parameter

By varying the count of the parameter

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

Super Class or Base Class or Parent


Class

Sub Class or Derived Class or Child


Class

What are the Advantages of Inheritance


1. Reusability of the code.
2. To Increase the reliability of the code.
3. To add some enhancements to the base class.

Inheritance achieved in two different forms


1. Classical form of Inheritance
2. Containment form of Inheritance
Classical form of Inheritance
A

Super Class or Base Class or


Parent Class

Sub Class or Derived Class or


Child Class
We can now create objects of classes A and B independently.
B

Example:
A a;

//a is object of A

B b;

//b is object of B

In Such cases, we say that the object b is a type of a. Such relationship


between a and b is referred to as is a relationship
Example
1. Dog is a type of animal
2. Manager is a type of employee
3. Ford is a type of car

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)

2. Multilevel Inheritance (Derived from a


Derived Class)
A

C
4. Hierarchical Inheritance (One Super class, Many
Subclasses)
A

/** A bank account has a balance that can be changed by deposits


and withdrawals.*/
public class BankAccount
/** Withdraws money from
account*/
{
public void withdraw(double
private double balance;
amount)
/* bank account with a zero
{
balance. */
balance = balance - amount;
public BankAccount()
}
{
/** Gets the current balance */
balance = 0;
public double getBalance()
}
{
/** bank account with a given
balance. */
return balance;
public BankAccount(double
}
initialBalance)
}
{
balance = initialBalance;
}
/**Deposits money into the bank
account.*/

public void deposit(double

63

Extending the class


/** An account that earns interest at a fixed rate. */
public class SavingsAccount extends BankAccount
{
private double interestRate;
/** Constructs a bank account with a given interest rate. @param
rate the interest rate */
public SavingsAccount(double rate)
{
interestRate = rate;
}
/** Adds the earned interest to the account balance. */
public void addInterest()
{
double interest = getBalance() * interestRate / 100;
deposit(interest);
}
}
64

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));
}
}

class BedRoom extends HallRoom


{
int height_1;
BedRoom()
{
length = 10;
breadth = 20; height = 30;
height_1 = 40;
}
void BedRoom_Volume1()
{
System.out.println("The Volume of the the BedRoom is:" + (length *
breadth * height * height_1));
}
}
class MainRoom
{
public static void main(String [] args)
{
BedRoom br = new BedRoom();
br.Room_Area();
br.HallRoom_Volume();
br.BedRoom_Volume1();
}
}

//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));
}
}

class BedRoom extends Room


{
void BedRoom_Volume()
System.out.println("The Volume of the BedRoom is:" + (length *
breadth * height));
}
}
class MainRoom
{
public static void main(String [] args)
{
HallRoom hr =new HallRoom();
BedRoom br = new BedRoom();
hr.HallRoom_Area();
br.BedRoom_Volume();
}
}

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();
}
}

Calling Super class Method

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

The this keyword is the name of a reference that refers to a calling


object itself. One of its common uses is to reference a classs
hidden data fields.
A hidden instance variable can be accessed by using the keyword
this
Example

75

this keyword to invoke constructor


If a class has multiple constructors, it is better to implement them using
this(arg-list) as much as possible. In general, a constructor with no or
fewer arguments can invoke the constructor with more arguments using
this(arg-list).
Example:

76

Super Keyword in Inheritance


The purpose of the super keyword:
1. Using super to call Superclass Constructors
2. Using super to call Superclass Methods
1. Using super to Call Superclass Constructor
A Subclass can call a constructor method defined by its superclass by
use of the following form of super:
super (parameter list)
Here, parameter list specifies any parameter needed by the
constructor in the superclass, super() must always be the first statement
executed inside a subclass constructor.
Restriction of the Subclass constructor
1. super may only be used within a subclass constructor method.
2. The call to superclass constructor must appear as the first
statement
within the subclass constructor
3. The parameters in the super call must match the order and type
of
the instance variable declared in the superclass.

Calling Super class Constructor

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();
}
}

//super keyword in Multilevel Inheritance


class Room
{
protected int length, breadth, height;
Room(int length, int breath)
{
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 breath, int height)
{
super(length,breath);
this.height = height;
}
void HallRoom_Volume()
{
System.out.println("The Volume of the HallRoom is:" + (length * breadth *
height));
}
}

class BedRoom extends HallRoom


{
int height_1;
BedRoom(int length, int breath, int height, int height_1)
{
super(length,breath,height);
this.height_1 = height_1;
}
void BedRoom_Volume_1()
{
System.out.println("The Volume 1 of the BedRoom is:" + (length *
breadth * height
* height_1));
}
}
class MainRoom
{
public static void main(String [] args)
{
BedRoom br =new BedRoom(10,20,30,40);
br.Room_Area();
br.HallRoom_Volume();
br.BedRoom_Volume_1();
}

//super keyword call Super Class Methods


class Room
{
void Room_Super()
{
System.out.println("The Room Base is Displayed");
}
}
class HallRoom extends Room
{
void HallRoom_Intermetiate()
{
System.out.println("The Hall Room is Displayed");
}
}
class BedRoom extends HallRoom
{
void BedRoom_Sub()
{
super.Room_Super();
super.HallRoom_Intermetiate();
System.out.println("The Bed Room is Displayed");
}
}
class MainRoom
{
public static void main(String [] args)
{
BedRoom br = new BedRoom();
br.BedRoom_Sub();
}
}

Final Keyword in Inheritance


What is the purpose of final keyword?
1. Cant initialize to variable again and again (Equivalent to Constant)
2. Cant Method Overriding
3. Cant Inherited

1. Cant initialize to variable again and again (Equivalent to Constant)


class Final
{
public static void main(String args[])
{
final int a = 45;
a = 78; //cannot assign the value to final Variable
System.out.println("The A Value is:" + a);
}
}

2. Cant Method Overriding


class Super
{
final void Super_Method()
{
System.out.println("This is Super Method");
}
}
class Sub extends Super
{
//Super method in sub cannot override Super_Method() in super;
Overridden
//method is final
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();
} }

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();
}
}

Understanding static Members:


There will be times when you will want to define a class member that will be
used independently of any object of that class.
Normally a class member must be accessed only in conjunction with an object
of its class. However, it is possible to create a member that can be used by
itself, without reference to a specific instance.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object.
You can declare both methods and variables to be static. The most common
example of a static member is main( ). main( ) is declared as static because
it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables.

Methods declared as static have several restrictions:


They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.

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

Accessing Static Members outside the class:


class StaticDemo
{
static int a;
int b;
static void display()
{
System.out.println(Static Data As value is: + a);
}
void putdata()
{
System.out.println(Non-static Data Bs value is:+b);
}
}
class Demo
{
public static void main(String args[])
{
StaticDemo s = new StaticDemo();
StaticDemo.a = 10;
//Initialize Static Variable
s.b = 20;
StaticDemo.display();
// Invoking Static Method
s.putdata();
}
}

Converting between subclass and


superclass
types
Subclass references can be converted to superclass references.
Example:
class BankAccount
{}
class SavingsAccount extends BankAccount
{
SavingsAccount collegeFund = new SavingsAccount(10);
BankAccount anAccount = collegeFund;
}
The instanceof operator tests whether an object belongs to a particular
type.

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

Interesting point on subclass


An abstract method cannot be contained in a non-abstract class. If a
subclass of an abstract superclass does not implement all the abstract
methods, the subclass must be defined abstract.
An abstract class cannot be instantiated using the new operator, but you
can still define its constructors, which are invoked in the constructors of its
subclasses.
A class that contains abstract methods must be abstract. However, it is
possible to define an abstract class that contains no abstract methods.
A subclass can be abstract even if its superclass is concrete.
A subclass can override a method from its superclass to define it abstract.

93

//Abstract Class Implementation


abstract class A
{
abstract void callme( ); // Abstract Method
void callmetoo( )
// Concrete Method
{
System.out.println("This is a Concrete method");
}
}
class B extends A
{
void callme( ) //Redefined for the Abstract Method
{
System.out.println("B's Implementation of Callme");
}
}
class MainRoom
{
public static void main(String [] args)
{
B b = new B( );

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();
}

How to Interface implements to the


Classes
Syntax:
class class_name implements interface_name
{
//Member of the Classes
//Definition of the Interfaces
}
Ex:
interface student
{
int slno = 12345;
String name = "CCET";
public void print_details();
}
class Inter_Def implements student
{
public void print_details()
{
System.out.println("The Serial Number is:" + slno);
System.out.println("The Student name is:" + name);
}
}

Difference between Abstract Classes and Interfaces

Abstract classes

Interfaces

Abstract classes are used only when Interfaces can be implemented by


there
classes
is a is-a type of relationship that are not related to one
between the
another.
classes.
You cannot extend more than one You can implement more than one
abstract class.
interface.
it contains both abstract methods Interface contains
and non Abstract Methods
methods
By default, Abstract Class data By default, data
members are Friendly.
Interface is Final.

all

abstract

members

in

With abstract classes, you are With Interfaces, you are merely
grabbing
extending
away each classs individuality.
each classs functionality.

Difference between Classes and Interfaces


1. Interface is little bit like a class... but interface is lack in instance
variables....that is
you can't create object for it.
2. Interfaces are developed to support multiple inheritances.
3. The methods present in interfaces are pure abstract.
4. The access specifiers public, private, protected are possible with classes. But
the interface uses only one specifier public.
5. Interfaces contain only the method declarations.... no definitions.......
6. In Class the variable declaration as well as initialization, but interface only
for initializing.

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

public void disp_B()


{
System.out.println("B's value: "+b);
}
public void disp_C()
{
System.out.println("C's value: "+c);
}
public void add()
{
System.out.println("Add is: "+ (a+b+c));
}
}
class Interface3 {
public static void main(String args[])
{
Derived d = new Derived();
d.disp_A();
d.disp_B();
d.disp_C();
d.add();
}
}

Output:
A's value: 10
B's value: 20
C's value: 30
Add is: 60

//HYBRID INHERITANCE USING INTERFACES


class Student
{
int rollno;
void get_rollno(int r)
{
rollno = r;
}
}
class Academic extends Student
{
int m1,m2,m3;
float avg, tot;
void get_marks(int mk1,int mk2,int mk3)
{
m1=mk1;
m2=mk2;
m3=mk3;
}
void process_avg()
{
tot = m1+m2+m3;
avg = tot/3;
}
}
interface Sports
{
String game = "Football";
public void disp_game();
}

Class

A
Interfac
e

Extension
Class

Extension
Class

D
Implementation

class Display extends Academic implements Sports


{
void disp_details()
{
System.out.println("Roll No. "+ rollno);
System.out.println("Mark 1: "+ m1);
System.out.println("Mark 2: "+m2);
System.out.println("Marks 3: "+m3);
System.out.println("Total Marks: "+ tot);
System.out.println("Average: "+ avg);
}
public void disp_game()
{
System.out.println("Game: "+ game);
}
}
class HybridInterface
{
public static void main(String args[])
{
Display d = new Display();
d.get_rollno(1001);
d.get_marks(98,78,58);
d.process_avg();
d.disp_details();
d.disp_game();
}
}

Output:
Roll No. 1001
Mark 1: 98
Mark 2: 78
Marks 3: 58
Total
Marks:
234.0
Average: 78.0
Game: Football

What is Partial Implementation?


The Interface is implementation to the Abstract class is called Partial
Implementation.
interface Interface
{
public void interface_one();
}
abstract class Abstract implements Interface
{
public void interface_one()
{
System.out.println("Interface methods in Abstract Class");
}
public void disp_concrete()
{
System.out.println("Concrete Method in Abstract Class");
}
abstract void disp_abstract();
}

class Partial extends Abstract


{
void disp_abstract()
{
System.out.println("Abstract method Definition in Inherited Class");
}
}
class Partial_Interface
{
public static void main(String args[])
{
Partial p = new Partial();
p.interface_one();
p.disp_concrete();
p.disp_abstract();
}
}
Output:
Interface methods in Abstract Class
Concrete Method in Abstract Class
Abstract method Definition in Inherited Class

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

2. Local Inner Class:


Local Classes are never declared with an access specifier (that is,
public or private).
Their scope is always restricted to the block in which they are
declared.
Local classes have a great advantage: they are completely hidden
from the outside world not even other code in the Outer Class can
access them.
No method except the method containing the Inner class has any
knowledge of the Inner Class.
class Outer {
public void disp_Outer()
{
System.out.println("Outer Class Method");
class Inner
{
void disp_Inner()
{
System.out.println("Inner Class Method");
}
}
Inner in = new Inner();
in.disp_Inner();

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.

4.Static Inner Class:


. To hide the inner class inside another, but dont need the inner class to
have a reference to the outer class object, static inner class can be used.
. The generation of that reference can be suppressed by declaring the
inner class static.
class Outer {
static class Inner
{
void display() {
System.out.println("Inner class reference is: " + this);
}
}
}
class StaticInner
{
public static void main(String[] args)
{
Outer.Inner n = new Outer.Inner();
n.display();
}
}
Output:

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

public int hashCode()

returns the hashcode number for this object.

public boolean equals(Object obj)

compares the given object to this object.

protected Object clone() throws


CloneNotSupportedException

creates and returns the exact copy (clone) of this object.

public String toString()

returns the string representation of this object.

protected void finalize()throws


Throwable

is invoked by the garbage collector before object is being


garbage collected.

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.

Você também pode gostar