1 / 60

JAVA WORKSHOP

JAVA WORKSHOP. 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.

Télécharger la présentation

JAVA WORKSHOP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Agenda • Encapsulation • Type Casting • Methods • Method Overloading • Method Overriding • Constructors • Packages • Access Specifiers

  3. Encapsulation • Encapsulation is the binding up of data and methods into a unit i.e class class Student { intsno; int marks; String sname; data void getPercentage() {---} void display() methods {---} } • The class definition is the foundation for encapsulation CLASS DATA METHODS

  4. 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 Student { private sno; private sname; private marks; privat data or fields public CLASS CLASS DATA METHODS

  5. //public methods public void setSno(intsno) { this.sno=sno; } public void setSname(intsname) { this.sname=sname; } public void setMarks(int marks) { this.marks=marks; } public float getPercentage() { return (marks/600)*100; }

  6. 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

  7. 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

  8. 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 • .

  9. 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: inti = 65; ex: float f = 12.5f; char ch = (char) i; inti=(int)f;

  10. 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

  11. Variables and Methods Class: Animal Data/Variables Food; Sound; Methods eat() talk() • Variables or State is the way in which object is defined • Methods are the things that object can do(actions) on data ddd Goat Lion Dog Food:meat Sound:roar eat()-eats meat Talk()-roars Food:biscuits Sound:bark eat()-eats biscuits Talk()-it barks Food:grass Sound:bleat Eat()-eats grass Talk()-bleats L 5.4

  12. 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 .

  13. 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

  14. 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 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; } }

  15. 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

  16. 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; } }

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

  18. output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625

  19. 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 } }

  20. // A simple example of inheritance. // Create a superclass. class A { inti, 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)); } }

  21. 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

  22. class Animal { void move() { System.out.println ("Animals can move"); } } class Dog extends Animal { void move() { System.out.println ("Dogs can walk and run"); } }

  23. 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 } }

  24. Output:

  25. Difference between overloading and overriding Overloading Overriding • Must have different 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. • Must have argument list of 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.

  26. 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

  27. 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 { introllNo; String name; Student () { rollNo = 101; name = “Kiran”; } }

  28. A program to initialize student details using default constructor and display the same. class Student { introllNo; 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); } }

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

  30. output

  31. 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 { introllNo; String name; Student (int r, String n) { rollNo = r; parameters name = n; } }

  32. //A program to initialize student details using Parameterized constructor and display the same. class Student { introllNo; 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); } }

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

  34. output

  35. 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

  36. 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; }

  37. // 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; } }

  38. 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);

  39. // 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

  40. 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 • Inbuilt packagegs. Packages available through java software installation Ex: lang , io , awt, util, awt etc, 2. User defined packages Packages created by programmers.

  41. Java API:

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

  43. 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 (inti=0; i<3; i++) current[i].show(); OUTPUT: } K. J. Fielding: $123.23 } Will Tell : $157.02 • -->>Tom Jackson: $-12.33

  44. Save, 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 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.

  45. 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

  46. 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.

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

  48. 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 }

  49. 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

  50. 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

More Related