Encapulation

Download Report

Transcript Encapulation

Presented By
Venkateswarlu. B
Assoc Prof of IT Dept
Newton’s Institute of Engineering
Agenda
 Encapsulation
 Type Casting
 Methods
 Method Overloading
 Method Overriding
 Constructors
 Packages
 Access Specifiers
Encapsulation
 Encapsulation is the binding up of data and methods into a unit i.e class
CLASS
DATA
METHODS

class Student
{
int sno;
int marks;
String sname;
void getPercentage()
{---}
void display()
{---}
}
The class definition is the foundation for encapsulation
data
methods
 Encapsulation keeps data and methods safe from
outside interference and misuse.
 Encapsulation is the technique of making the data in a
class private and providing access to the data via public
methods.
private
 Ex:
CLASS
CLASS
class Student
DATA
{
private sno;
METHODS
private sname;
private marks;
privat data or fields public
 //public methods
public void setSno(int sno)
{
this.sno=sno;
}
public void setSname(int sname)
{
this.sname=sname;
}
public void setMarks(int marks)
{
this.marks=marks;
}
public float getPercentage()
{
return (marks/600)*100;
}
public void display()
{
System.out.println(“Sno is”+sno);
System.out.println(“Sname is”+sname);
System.out.println(“Percentage is”+getPercentage());
}
}
public class StudentDetails
{
public static void main(String args[])
{
Student s1= new Student(); //creates object
s1.setSno(1201);
//sets the value for sno
s1.setSname(“Sai Ram”); //sets the value for sname
s1.setMarks(501);
//set s the value for marks
s1.display();
//displays student details
}
o/p: Sno is 1201
}
Sname is Sai Ram
Percentage is 83.5
Type Conversion and Casting
• Type Casting: Converting one data type into another
data type is called casting
General form : (target-type) value;
(int) 3.6;
Data type represents the type of the data stored into a
variable.
There are two kinds of data types:
• Primitive Data type: Primitive data type represents
singular values.
e.g.: byte, short, int, long, float, double, char, boolean.
L 3.5
Here Conversion is done in two ways
– Implicit type conversion
• Carried out by compiler automatically
conditions:
a) The two types are compatible
b) The destination type is larger than source type
General form : (destination-type) source value;
float f= (float)8;
– Explicit type conversion (Casting)
• Carried out by programmer using casting
• To create a conversion between two incompatible
types casting is used
.
Using casting we can convert a primitive data type into another
primitive data type.
This is done in two ways, widening and narrowing
Widening: Converting a lower data type into higher data type is
called widening.
ex: char ch = 'a';
ex: int n = 12;
int n = (int ) ch;
float f = (float) n;
Narrowing: Converting a higher data type into lower data type is
called narrowing.
ex: int i = 65;
ex: float f = 12.5f;
char ch = (char) i;
int i=(int)f;
Naming conventions specify the rules to be followed by a
Java programmer while writing the names of packages, classes,
methods etc.
• Package names are written in small letters.
ex: java.io, java.lang, java.awt etc
• Each word of class name and interface name starts with a capital
ex: Sample, AddTwoNumbers
•Method names start with small letters then each word start with a
capital
ex: sum (), sumTwoNumbers (), minValue ()
· Variable names also follow the same above method rule
ex: sum, count, totalCount
· Constants should be written using all capital letters
ex: PI, COUNT
· Keywords are reserved words and are written in small letters.
ex: int, short, float, public, void
Variables and Methods
 Variables or State is the way in which object is defined
 Methods are the things that object can do(actions) on data
Class: Animal
ddd
Data/Variables
Food;
Sound;
Methods
eat()
talk()
Lion
Dog
Goat
Food:meat
Sound:roar
Food:biscuits
Sound:bark
Food:grass
Sound:bleat
eat()-eats meat
Talk()-roars
eat()-eats
biscuits
Talk()-it barks
Eat()-eats
grass
Talk()-bleats
L 5.4
 A method represents a group of statements to perform
a task
 General form of a method definition:
type name(parameter-list)
method header
{
(or) signature
method body
//staments …
…
}
 Components:
1) type - type of values returned by the method
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
.
class Animal
{
public String food;
public String sound;
public void eat()
{
S.o.p(“It eats”+food);
}
public void talk()
{
s.o.p( “It “+sound+”s”);
}
}
Method signature
Method signature
Class AnimalsInfo
{
public static void main(String args[])
{
System.out.println(“lion”);
Animal lion=new Animal();
lion.food=“meat”; lion.sound=“roar”;
lion.eat();//displays it eats meat
lion.talk();//displays it roars
System.out.println(“dog”);
Animal dog=new Animal();
dog.food=“biscuits”; dog.sound=“bark”;
dog.eat();//displays it eats biscuits
dog.talk();//displays it barks
System.out.println(“goat”);
Animal goat=new Animal();
goat.food=“grass”;goat.sound=“gleat”;
goat.eat();//displays it eats grass;
goat.talk();//displays it gleats;
}
}
OUTPUT:
Method Overloading
 If two or more methods are written with same name but
difference in parameters is called Overloading
The difference may be
 In the no. of parameters.
void add (int a, int b)
void add (int a, int b, int c)
 In the data types of parameters.
void add (int a, int b)
void add (double a, double b)
 There is a difference in the sequence of parameters.
void swap (int a, char b)
void swap (char a, int b)
 Return type ,accessibiliry may be same or different
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;
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Inheritance
It is the mechanism of aquring the properties and methods from super
class to sub class is
Class superclass
{
//properties
//methods
}
Class subclass extends Superclass
{
//properties
//methods
}
}
 // A simple example of inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
Overriding
 Writing two methods with same name and same




signature in super class and sub class is called method
overriding.
In overriding the sub class method will override the
super class method
Each parent class method may be overridden at most
once in any one sub class(you can not have two
identical methods in the same class)
An overriding method must not be less accessible than
the method it overrides.
An overriding method must not throw any checked
Exceptions that are not declared for the overridden
method
class Animal
{
void move()
{
System.out.println ("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
System.out.println ("Dogs can walk and run");
}
}
 public class OverRide
{
public static void main(String args[])
{
Animal a = new Animal (); // Animal reference and object
Animal b = new Dog (); // Animal reference but Dog object
a.move (); // runs the method in Animal class
b.move (); //Runs the method in Dog class
}
}
Output:
Difference between overloading and overriding
Overloading
Overriding
 Must have different
 Must have argument list of
arguments list
 Return type may be chosen
freely
 In same class they can exist
in any number
 JVM can identify methods
separately by the difference in
their parameters.
identical type and order
 Return type must be identical
to the method it overrides
 Two identical methods in
the same class can not exist
 JVM executes a method
depending on the type of the
object.
Constructors
 Constructor is similar to a method that initializes the







instance variables of a class.
A constructor name and class name must be same.
A constructor may have or may not have parameters.
Parameters are local variables to receive data.
A constructor does not return any value, not even void
A constructor is called and executed at the time of
creating an object.
A constructor is called only once per object.
Constructors are two types
default or zero argument constructor
 A constructor without parameters is called default
constructor.
 Default constructor is used to initialize every object with same
data
class Student
{
int rollNo;
String name;
Student ()
{
rollNo = 101;
name = “Kiran”;
}
}
 A program to initialize student details using default
constructor and display the same.
class Student
{
int rollNo;
String name;
Student ()
{
rollNo = 101;
default constructor
name = "Suresh";
}
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student ();
System.out.println ("s1 object contains: ");
s1.display ();
Student s2 = new Student ();
System.out.println ("s2 object contains: ");
s2.display ();
}
}
output
parameterized constructor
 A constructor with one or more parameters is called
parameterized constructor.
 parameterized constructor is used to initialize each object with
different data.
EX: class Student
{
int rollNo;
String name;
Student (int r, String n)
{
rollNo = r;
parameters
name = n;
}
}
 //A program to initialize student details using Parameterized
constructor and display the same.
class Student
{
int rollNo;
String name;
Student (int r, String n)
{
rollNo = r;
name = n;
}
void display ()
{
System.out.println ("Student Roll Number is: " + rollNo);
System.out.println ("Student Name is: " + name);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student (101, “Suresh”);
System.out.println (“s1 object contains: “ );
s1.display ();
Student s2 = new Student (102, “Ramesh”);
System.out.println (“s2 object contains: “ );
s2.display ();
}
}
output
 A programmer uses default constructor to initialize
different objects with same data
 Parameterized constructor is used to initialize each
object with different data
 If no constructor is written in a class then java
compiler will provide default constructor with default
values
Overloading Constructors
 In addition to overloading normal methods, we can also overload
constructor methods.
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// 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);
}
}
o/p:




The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Packages
 A package is a container of classes and interfaces.
 A package represents a directory that contains
related group of classes and interfaces.
There are two kinds of packages
1. Inbuilt packagegs.
Packages available through java software installation
Ex: lang , io , awt, util, awt etc,
2. User defined packages
Packages created by programmers.
Java API:
Creating a Package:
 The first statement in the program must be package statement while
creating a package.
 package myPackage;
class MyClass1 { … }
class MyClass2 { … }
 Means that all classes in this file belong to the myPackage package.
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n; bal = b;
}
void show()
{
if (bal>0)
System.out.print("-->> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for (int i=0; i<3; i++) current[i].show(); OUTPUT:
}
K. J. Fielding: $123.23
}
Will Tell : $157.02

-->>Tom Jackson: $-12.33
 Save, compile and execute:
1) Save the file in the directory MyPack with the
name AccountBalance.java
2) Compile the file
Note:Make sure that the resulting .class file is
also in the MyPack directory
3) Make the parent of MyPack your current
directory
or
set access to MyPack in CLASSPATH variable as
>set CLASSPATH=%CLASSPATH%;loaction of MyPack;.
4) run: java MyPack.AccountBalance
 Make sure to use the package-qualified class name.
Package Hierarchy
 To create a package hierarchy, separate each
package name with a dot:
package com.infosys.financialDomain;
 A package hierarchy must be stored accordingly in
the file system:
Location:
com\infosys\financialDomain
Import Statement
 The import statement occurs immediately after the
package statement and before the class statement
package myPackage;
import com.infosys.FinancialDomain.*;
class myClass
{…}
 The Java system accepts this import statement by default:
import java.lang.*;
 This package includes the basic language functions.
Without such functions, Java is of no much use.
Example program
 A package MyPack with one public class Balance.
 The class has two same-package variables: public constructor
and a public show method.
package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n; bal = b;
}
public void show()
{
if (bal<0) System.out.print("-->> ");
System.out.println(name + ": $" + bal);
}
}
The importing code has access to the public class Balance of
the MyPack package and its two public members:
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show();
}
OUTPUT: J. J. Jaspers:$ 99.88
}
Access Specifiers
 Access Specifiers:
 An access specifier is a key word that represents how to





access a member of a class.
The access specifiers in java are
private: private members of a class are not available
outside the class.
The scope of private members is within the class
public: public members of a class are available
anywhere outside the class.
The scope of public members is global scope
 protected: protected members are available in the




same package,but not in the other packages.
The scope of protected members is within the package
Note:protected members of a class are avaible to
subclasses evnthough the sub classes are in another
package
default: If no access specifier is used then default
specifier is used by java compiler.
Default members of a class are available in the same
package but in the other package
The scope of protected members is within the package
Determining Access to Class Members
Visibility
Public
Protected Default
Private
From the same class
Yes
Yes
Yes
Yes
From any class in the same
package
Yes
Yes
Yes
No
From a subclass in the
same package
Yes
Yes
Yes
No
From a subclass outside the Yes
same package
Yes,
through
inheritance
No
No
From any non-subclass
class outside the package
No
No
No
Yes
 Package same
CCcC
Class Bc
Package another
clas
Class A
Private
Public
Protected
default
Class C
A program to create class A with different access
specifiers.
//create a package same
package same;
public class A
{
private int a=1;
public int b = 2;
protected int c = 3;
int d = 4;
}
Compile:
A program for creating class B in the same
package.
//class B of same package
package same;
import same.A;
public class B
{
public static void main(String args[])
{
A obj = new A();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Compiling the above program:
A program for creating class C of another
package.
package another;
import same.A;
public class C
{
public static void main(String args[])
{
C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Compiling the above program:
 Change output
A program for creating class C of another
package as sub class of A
package another;
import same.A;
public class C extends A
{
public static void main(String args[])
{
C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(obj.c);
System.out.println(obj.d);
}
}
Compiling the above program: