presented by venkateswarlu. b assoc prof of it dept newton’s institute of engineering

60
JAVA WORKSHOP Presented By Venkateswarlu. B Assoc Prof of IT Dept Newton’s Institute of Engineering

Upload: ernest-sherman

Post on 29-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Encapulation

JAVA WORKSHOPPresented ByVenkateswarlu. B Assoc Prof of IT DeptNewtons Institute of EngineeringAgendaEncapsulationType CastingMethodsMethod OverloadingMethod OverridingConstructorsPackagesAccess SpecifiersEncapsulationEncapsulation is the binding up of data and methods into a unit i.e class class Student { int sno; int marks; String sname; data void getPercentage() {---} void display() methods {---} } The class definition is the foundation for encapsulation

CLASS

DATAMETHODSEncapsulation 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. privateEx: class Student { private sno; private sname; private marks; privat data or fields public

CLASS

CLASS

DATAMETHODS//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.5L 3.5Type Conversion and CastingType Casting: Converting one data type into another data type is called castingGeneral 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.Here Conversion is done in two ways Implicit type conversionCarried out by compiler automatically conditions: a) The two types are compatible b) The destination type is larger than source typeGeneral form : (destination-type) source value; float f= (float)8; Explicit type conversion (Casting)Carried out by programmer using castingTo 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 capitalex: Sample, AddTwoNumbersMethod names start with small letters then each word start with a capitalex: sum (), sumTwoNumbers (), minValue () Variable names also follow the same above method ruleex: sum, count, totalCount Constants should be written using all capital lettersex: PI, COUNT Keywords are reserved words and are written in small letters.ex: int, short, float, public, voidL 5.4Variables and Methods

Variables or State is the way in which object is defined Methods are the things that object can do(actions) on data

dddClass: Animal

Data/VariablesFood;Sound;

Methodseat()talk()Food:meatSound:roar

eat()-eats meatTalk()-roarsFood:biscuitsSound:bark

eat()-eats biscuitsTalk()-it barksFood:grassSound:bleat

Eat()-eats grassTalk()-bleatsLionDogGoatA method represents a group of statements to perform a taskGeneral 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 method2) name is the name of the method3) 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 signatureMethod signature Class AnimalsInfo { public static void main(String args[]) { OUTPUT: System.out.println(lion); Animal lion=new Animal();lion.food=meat; lion.sound=roar;lion.eat();//displays it eats meatlion.talk();//displays it roars System.out.println(dog); Animal dog=new Animal();dog.food=biscuits; dog.sound=bark;dog.eat();//displays it eats biscuitsdog.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;} }

Method OverloadingIf two or more methods are written with same name but difference in parameters is called Overloading The difference may beIn 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 differentclass 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 parametersa: 10a and b: 10 20double a: 123.25Result of ob.test(123.25): 15190.5625InheritanceIt is the mechanism of aquring the properties and methods from super class to sub class isClass 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 methodEach 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 methodclass 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 objecta.move (); // runs the method in Animal classb.move (); //Runs the method in Dog class}}Output:

Difference between overloading and overridingOverloadingOverridingMust have different arguments listReturn type may be chosen freely In same class they can exist in any numberJVM can identify methods separately by the difference in their parameters.Must have argument list of identical type and orderReturn type must be identical to the method it overrides Two identical methods in the same class can not existJVM 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 voidA 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 constructorname = "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 constructorA 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 dataParameterized constructor is used to initialize each object with different dataIf no constructor is written in a class then java compiler will provide default constructor with default valuesOverloading ConstructorsIn addition to overloading normal methods, we can also overload constructor methods. class Box {double width;double height;double depth;// constructor used when all dimensions specifiedBox(double w, double h, double d) {width = w;height = h;depth = d; }// constructor used when no dimensions specifiedBox() {width = -1; // use -1 to indicate height = -1; // an uninitializeddepth = -1; // box }

// constructor used when cube is createdBox(double len) {width = height = depth = len; }// compute and return volumedouble volume() {return width * height * depth; }}class OverloadCons {public static void main(String args[]) {// create boxes using the various constructorsBox mybox1 = new Box(10, 20, 15);Box mybox2 = new Box();Box mycube = new Box(7);double vol;// get volume of first boxvol = mybox1.volume();System.out.println("Volume of mybox1 is " + vol);// get volume of second boxvol = mybox2.volume();System.out.println("Volume of mybox2 is " + vol);// get volume of cubevol = 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.0Volume of mybox2 is -1.0Volume of mycube is 343.0PackagesA 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 packagesInbuilt 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>Tom Jackson: $-12.33Save, compile and execute: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 directory3) 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.AccountBalanceMake sure to use the package-qualified class name.

Package HierarchyTo 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 StatementThe 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 programA 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