Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter No. 2 Classes, Objects & Methods

Similar presentations


Presentation on theme: "Chapter No. 2 Classes, Objects & Methods"— Presentation transcript:

1 Chapter No. 2 Classes, Objects & Methods

2 Defining a class, creating object
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created A class in Java can contain: Fields (data members) methods constructors blocks nested class and interface

3 Syntax to declare a class:
class class_name {       field declaration;       method declaration;   }  

4 Student s1=new Student();
Object An object is an instance of a class. Object determines the behaviour of the class. Student s1=new Student(); Student s2=new Student(2, “ABC”); Student s3=new Student(s1);

5 accessing class members
Instance variables and methods are accessed via created objects. object_name.variableName; object_name.MethodName();

6 Object and Class Example
class Student{    int id=1; //field or data member or instance variable    String name=“ABC”;       public static void main(String args[]){     Student s1=new Student(); //creating an object of Student     System.out.println(s1.id);//accessing member through reference variable   System.out.println(s1.name);    }   }   OUTPUT: 1 ABC

7 Constructors & methods
Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. Rules for creating java constructor Constructor name must be same as its class name Constructor must have no explicit return type

8 Types of java constructors
Default constructor (no-arg constructor) Parameterized constructor Copy constructor Example of Constructor

9 class Student { int id; String name; Student(int i,String n) { id = i; name = n; } void display() System.out.println(id+" "+name); } public static void main(String args[]) Student s1 = new Student4(111,"Karan"); Student s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); }

10 Constructor Overloading in Java
In Java a class can have any number of constructors that differ in parameter lists is called Constructor overloading . The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

11 class Student { int id; String name; int age; Student(int i,String n) id = i; name = n; } Student(int i,String n,int a) age=a; void display() { System.out.println(id+" "+name+" "+age); }  public static void main(String args[]) {       Student s1 = new Student(111,"Karan");       Student s2 = new Student(222,"Aryan",25);       s1.display();       s2.display();      }   }  

12 Method Overloading in Java
A Java method is a collection of statements that are grouped together to perform an operation. Creating Method modifier returnType nameOfMethod (Parameter List) { // method body } If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.

13 class Overloading { void sum(int a,long b) { System. out
class Overloading { void sum(int a,long b) { System.out.println(a+b); } void sum(int a,int b,int c) System.out.println(a+b+c); public static void main(String args[]) Overloading obj=new Overloading(); obj.sum(20,20); obj.sum(20,20,20); }

14 Nesting of Methods When a method in java calls another method in the same class, it is called Nesting of methods. The below Java Program to Show the Nesting of Methods.

15 import java.util.Scanner; public class Nest_Methods { int area(int l, int b) int ar = 6 * l * b; return ar; } int volume(int l, int b, int h) int ar = area(l, b); System.out.println("Area:"+ar); int vol ; vol = l * b * h; return vol; public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter length of cuboid:"); int l = s.nextInt(); System.out.print("Enter breadth of cuboid:"); int b = s.nextInt(); System.out.print("Enter height of cuboid:"); int h = s.nextInt(); Nest_Methods obj = new Nest_Methods(); int vol = obj.volume(l, b, h); System.out.println("Volume:"+vol); }

16 argument passing There are two ways to pass an argument to a method. But there is only call by value in java call-by-value : In this approach copy of an argument value is pass to a method. Changes made to the argument value inside the method will have no effect on the arguments. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside the method will affect the argument value.

17 ‘this’ Keyword this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.

18 class Student { int rollno; String name; Student(int rollno,String name) this.rollno=rollno; this.name=name; } void display() { System.out.println(rollno+" "+name); class TestThis2 {   public static void main(String args[]) Student s1=new Student(111,"ankit”);  Student s2=new Student(112,"sumit”);   s1.display();   s2.display();   } }  

19 command line arguments
Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program's name on the command line when it is executed. They are stored as strings in the String array passed to main( ).

20 public class CommandLine { public static void main(String args[]) for(int i = 0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } executing this program as shown here − D:\>javac CommandLine D:\>java CommandLine this is a command line

21 Output args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100

22 varargs: variable-length arguments
The varargs allows the method to accept zero or multiple arguments. If we don't know how many argument we will have to pass in the method, varargs is the better approach. Syntax of varargs: return_type method_name(data_type... variableName){}  

23 class VarargsExample { static void display(String. values) System. out
class VarargsExample { static void display(String... values) System.out.println("display method invoked "); for(String s:values) System.out.println(s); } } public static void main(String args[]) display();//zero argument display("hello");//one argument display("my","name","is","varargs");//four arguments } Output: display method invoked hello My Name Is varargs

24 garbage collection Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects. It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.

25 finalize() method This method can be used to perform cleanup processing. Objects may hold other non-object resources such as file descriptors or system fonts. The garbage collector cannot free these resources. In order to free these resources we must use a finalize() method. protected void finalize(){}  

26 Visibility Control Java provides three types of visibility modifiers: public, private and protected. They provide different levels of protection as described below. Public Access: Any variable or method is visible to the entire class in which it is defined. But, to make a member accessible outside with objects, we simply declare the variable or method as public. A variable or method declared as public has the widest possible visibility and accessible everywhere. Friendly Access (Default): When no access modifier is specified, the member defaults to a limited version of public accessibility known as "friendly" level of access. The difference between the "public" access and the "friendly" access is that the public modifier makes fields visible in all classes, regardless of their packages while the friendly access makes fields visible only in the same package, but not in other packages.

27 Protected Access: The visibility level of a "protected" field lies in between the public access and friendly access. That is, the protected modifier makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages Private Access: private fields have the highest degree of protection. They are accessible only with their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses. In the case of overriding public methods cannot be redefined as private type. Private protected Access: A field can be declared with two keywords private and protected together. This gives a visibility level in between the "protected" access and "private" access. This modifier makes the fields visible in all subclasses regardless of what package they are in. Remember, these fields are not accessible by other classes in the same package.

28 Access modifier à public protected friendly private protected private Own class ü Sub class in same package û Other classes In same package in other package In other package

29 Arrays & Strings Types of arrays, creating an array
Array is a collection of similar type of elements that have contiguous memory location. Types of Array in java Single Dimensional Array Multidimensional Array

30 Syntax to Declare an Array in java
dataType arr[];   dataType arrayRefVar[][];    Instantiation of an Array in java arrayRefVar=new datatype[size];   arrayRefVar[][]=new datatype[size][size]; We can declare, instantiate and initialize the java array together by: int a[]={33,3,4,5}; int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  

31 class Testarray { public static void main(String args[]) int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; for(int i=0;i<3;i++) for(int j=0;j<3;j++) System.out.print(arr[i][j]+" "); } System.out.println(); } Output: 1 2 3 2 4 5 4 4 5

32 strings In java, string is basically an object that represents sequence of char values.  The java.lang.String class is used to create string object. creating String object String s="welcome";   (or) String s=new String("Welcome");

33 public class StringExample { public static void main(String args[]) String s1="java“; char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to string String s3=new String("example"); System.out.println(s1); System.out.println(s2); System.out.println(s3); } } OUTPUT: java strings example

34 String Class Methods 1. charAt() This function returns the character located at the specified index. For example: String str = “mmpolytechnic"; System.out.println(str.charAt(2)); Output : p 2. equalsIgnoreCase() This function determines the equality of two Strings, ignoring their case (upper or lower case doesn't matters with this fuction ). String str = "java"; System.out.println(str.equalsIgnoreCase("JAVA")); Output : true

35 3. indexOf() function returns the index of first occurrence of a substring or a character. Forms of indexOf() method: int indexOf(String str) It returns the index within this string of the first occurrence of the specified substring. int indexOf(String str, int fromIndex) It returns the index within this string of the first occurrence of the specified substring, starting at the specified index. For Example: String str=“MMPolytechnic"; System.out.println(str.indexOf('P')); System.out.println(str.indexOf(‘i', 3)); String subString=“tech"; System.out.println(str.indexOf(subString)); System.out.println(str.indexOf(subString,8)); Output:

36 4. length()  This function returns the number of characters in a String.
For example: String str = "Count me"; System.out.println(str.length()); Output : 8 5. replace() This method replaces occurances of character with a specified new character. String str = "Change me"; System.out.println(str.replace('m','M')); Output : Change Me

37 6. substring() This method returns a part of the string
6. substring() This method returns a part of the string.  substring() method has two forms, String substring(int begin) It will return substring starting from specified point to the end of original string. String substring(int begin, int end) The first argument represents the starting point of the substring and the second argument specify the end point of substring. For Example: String str = " "; System.out.println(str.substring(4)); Output : System.out.println(str.substring(4,7)); Output : 456

38 7. toLowerCase() This method returns string with all uppercase characters converted to lowercase.
For Example: String str = "ABCDEF"; System.out.println(str.toLowerCase()); Output : abcdef 8. toUpperCase() This method returns string with all lowercase character changed to uppercase. String str = "abcdef"; System.out.println(str.toUpperCase()); Output : ABCDEF

39 9. valueOf() This  function is used to convert primitive data types into Strings.
For example int num=35; String s1=String.valueOf(num); //converting int to String System.out.println(s1+"IAmAString"); Output: 35IAmAString 10. trim() This method returns a string from which any leading and trailing whitespaces has been removed. String str = " hello "; System.out.println(str.trim()); output : hello trim() method removes only the leading and trailing whitespaces.

40 11. toString() This method returns the string representation of the object used to invoke this method. 12. equals() This method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. For example String s1="java";   String s2="JAVA";   System.out.println(s1.equals(s2)); OUTPUT false

41 13. compareTo() It compares strings on the basis of Unicode value of each character in the strings. It returns positive number, negative number or 0. if s1 > s2, it returns positive number   if s1 < s2, it returns negative number   if s1 == s2, it returns 0   14. concat() This method combines specified string at the end of this string. It returns combined string. It is like appending another string. For Example String s1="java string";   s1.concat("is immutable");   Output java string is immutable

42 StringBuffer class String creates strings of fixed length, while StringBuffer creates strings of flexible length that can be modified in terms of both length and content. So StringBuffer class is used to create a mutable string object i.e StringBuffer class is used when we have to make lot of modifications to our string.

43 Important methods of StringBuffer class
append() This method will concatenate the string representation of any type of data to the end of the invoking StringBuffer object.  StringBuffer str = new StringBuffer("test"); str.append(123); System.out.println(str); Output : test123

44 StringBuffer str = new StringBuffer("test"); str.insert(4, 123);
insert() This method inserts one string into another. Here are few forms of insert() method. StringBuffer insert(int index, String str) StringBuffer insert(int index, int num) StringBuffer insert(int index, Object obj) Here the first parameter gives the index at which position the string will be inserted and string representation of second parameter is inserted into StringBuffer object. StringBuffer str = new StringBuffer("test"); str.insert(4, 123); System.out.println(str); Output : test123

45 setCharAt() method sets the character at the specified index to ch.
setCharAt(int index, char ch) Here index  is the index of the character to modify and ch is the new character. StringBuffer buff = new StringBuffer("AMIT"); buff.setCharAt(3, 'L'); System.out.println("After Set, buffer = " + buff); Output After Set, buffer = AMIL

46 setLength() method sets the length of the character sequence
setLength() method sets the length of the character sequence. The sequence is changed to a new character sequence whose length is specified by the argument. setLength(int newLength) newLength is the new length. StringBuffer buff = new StringBuffer("tutorials"); System.out.println("length = " + buff.length()); buff.setLength(5); System.out.println("buff after new length = " + buff); Output length = 9 buff after new length = tutor

47 Vectors Vector implements a DYNAMIC ARRAY.
Vectors can hold objects of any type and any number. Vector class is contained in java.util package.

48 Difference between Vector & Array
Sr. No. Vector Array 1 Vector can grow and shrink dynamically. Array can’t grow and shrink dynamically. 2 Vector can hold dynamic list of objects or primitive data types. Array is a static list of primitive data types. 3 Vector class is found in java.util package . Array class is found in java.lang (default) package. 4 Vector can store elements of different data types. Array can store elements of same data type. 5 Vector class provides different methods for accessing and managing vector elements. For accessing element of an array no special methods are available as it is not a class, but a derived type. 6 Syntax : Vector objectname=new Vector(); datatype arrayname[]=new datatype[size]; 7 Example: Vector v1=new Vector(); Example: int[] myArray={22,12,9,44};

49 Constructors of Vector Class
 Vector() -Constructs an empty vector. Vector list=new Vector(); Vector(int size) -Constructs an empty vector with the specified initial capacity. Vector list=new Vector(3);

50 Vector Methods  addElement(Object) Adds the specified object to the end of this vector, increasing its size by one.  Syntax : vect_object.addElement(Object); Example : If v is the Vector object , v.addElement(new Integer(10)); capacity() Returns the current capacity of this vector.  vect_object.capacity(); v. capacity();

51 elementAt(index) Returns the object at the specified index.
Syntax : vect_object.elementAt(index); Example : If v is the Vector object , v.elementAt(3); firstElement() Returns the first object of this vector.  vect_object.firstElement(); v. firstElement();

52 lastElement() Returns the last object of the vector. 
Syntax : vect_object.lastElement(); Example : If v is the Vector object , v. lastElement(); insertElementAt(Object, index) Inserts the specified object in this vector at the specified index.  vect_object.insertElementAt(object,index); v. insertElementAt(20,5);

53 indexOf(Object) Searches for the first occurrence of the given argument, testing for equality using the equals method.  Syntax : vect_object.indexOf(object); Example : If v is the Vector object , v. indexOf(20); indexOf(Object, begin_index) Searches for the first occurrence of the given argument, beginning the search at index, and testing for equality using the equals method. vect_object.indexOf(object,begin_index); v. indexOf(20,3);

54 lastIndexOf(Object) Returns the index of the last occurrence of the specified object in this vector. 
Syntax : vect_object.lastIndexOf(object); Example : If v is the Vector object , v. lastIndexOf(20);   isEmpty() Tests if this vector has no objects.  vect_object.isEmpty(); v. isEmpty();

55 setElementAt(Object, index) Sets the object at the specified index of this vector to be the specified object.  Syntax : vect_object.setElementAt(object, index); Example : If v is the Vector object , v. setElementAt(30,5); setSize(int) Sets the size of this vector.  vect_object.setSize(size); v. setSize(10);

56 size() Returns the number of objects in this vector. 
Syntax : vect_object.size(); Example : If v is the Vector object , v. size(); contains(Object) Tests if the specified object is present in this vector. Syntax : vect_object.cotains(object); v. contains(30); copyInto(Object[]) Copies the objects of this vector into the specified array Syntax : vect_object.copyInto(object[]); v. copyInto(anArray);

57 removeAllElements() Removes all objects from this vector and sets its size to zero. 
Syntax : vect_object.removeAllElements(); Example : If v is the Vector object , v. removeAllElements(); removeElement(Object)Removes the first occurrence of the argument from this vector.  Syntax : vect_object.removeElement(object); v. removeElement(30); removeElementAt(int)Deletes the component at the specified index.  Syntax : vect_object.removeElementAt(index); v. removeElementAt(5);

58 Wrapper classess in Java
Wrapper class in java provides the mechanism to convert primitive into object and object into primitive. There are mainly two uses with wrapper classes. To convert simple data types into objects constructors are used. To convert strings into data types (known as parsing operations) methods of type parseXXX() are used.

59 The automatic conversion of primitive into object is known as autoboxing and vice-versa unboxing.
Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double

60 Creating objects of the Wrapper classes
All the wrapper classes have constructors which can be used to create the corresponding Wrapper class objects. For example, Integer intObject = new Integer (34);  Integer intObject = new Integer (i);  Float floatObject = new Float(f); Double doubleObject = new Double(d); Long longObject = new Long(l); Where i,f,d,l are the variables of respective primitive types.

61 The most common methods of the Integer wrapper class are summarized in below table. Similar methods for the other wrapper classes are found in the Java API documentation. Method Purpose int i =Integer.parseInt(str) returns a signed decimal integer value equivalent to string str str=Integer.toString(i) returns a new String object representing the integer i byte b=intObject.byteValue() returns the value of this Integer as a byte double d=intObject.doubleValue() returns the value of this Integer as a double float f=intObject.float Value() returns the value of this Integer as a float int i=intObject.intValue() returns the value of this Integer as an int short s=intObject.shortValue() returns the value of this Integer as a short long l=intObject.longValue() returns the value of this Integer as a long

62 To convert any of the primitive data type value to a String, we use the valueOf() method of the String class which can accept any of the eight primitive types.  String s1= String.valueOf('a'); // s1="a"  String s2=String.valueOf(25); // s2=“25"  String s3=String.valueOf(10.5); //s3=“10.5”

63 Enumerated Types Enum in java is a data type that contains fixed set of constants. It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum constants are static and final implicitly. 

64 class EnumExample { public enum Season{ WINTER, SPRING, SUMMER, FALL } public static void main(String[] args) for (Season s : Season.values()) System.out.println(s); } } Output: WINTER SPRING SUMMER FALL

65 Inheritance Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. 

66 Types of inheritance in java
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. 

67 Output: barking... eating...
Single Inheritance Example class Animal { void eat() { System.out.println("eating..."); } class Dog extends Animal void bark() System.out.println("barking..."); class Inheritance {   public static void main(String args[]) Dog d=new Dog();   d.bark();   d.eat();   } }   Output: barking... eating...

68 System.out.println("eating..."); } class Dog extends Animal
Multilevel Inheritance Example class Animal {   void eat() { System.out.println("eating..."); }   class Dog extends Animal void bark() System.out.println("barking..."); class BabyDog extends Dog void weep() System.out.println("weeping..."); class Inheritance {   public static void main(String args[]) BabyDog d=new BabyDog();   d.weep();   d.bark();   d.eat();   } }   Output: weeping... barking... eating...

69 System.out.println("eating..."); } class Dog extends Animal
Hierarchical Inheritance Example class Animal {   void eat() { System.out.println("eating..."); }   class Dog extends Animal void bark() System.out.println("barking..."); class Cat extends Animal void meow() System.out.println("meowing..."); class Inheritance {   public static void main(String args[]) Cat c=new Cat();   c.meow();   c.eat();    } }   Output: meowing... eating...

70 Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. Rules for Java Method Overriding method must have same name as in the parent class method must have same parameter as in the parent class.

71 Output: Bike is running safely Example of method overriding
class Vehicle {   void run() { System.out.println("Vehicle is running"); }   class Bike extends Vehicle System.out.println("Bike is running safely");    public static void main(String args[]) Bike obj = new Bike();   obj.run();   Output: Bike is running safely

72 Dynamic method dispatch
Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to.

73 Example of Dynamic method dispatch
public class TestDog { public static void main(String args[]) Animal a = new Animal(); Dog b = new Dog(); a.move(); b.move(); a=b; } class Animal { public void move() System.out.println("Animals can move"); } class Dog extends Animal System.out.println("Dogs can walk and run");

74 super keyword In Java, super keyword is used to refer to immediate parent class of a child class. In other words super keyword is used by a subclass whenever it need to refer to its immediate super class.

75 Final Keyword In Java The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: variable method class

76 Java final variable If you make any variable as final, you cannot change the value of final variable(It will be constant). Example of final variable class Bike {    final int speedlimit=80;//final variable    void run()   speedlimit=100;     }    public static void main(String args[])  Bike obj=new  Bike();    obj.run();   }   Output: Compile Time Error

77 Java final method If you make any method as final, you cannot override it. Example of final method class Bike {     final void run() { System.out.println("running"); }   }    class Honda extends Bike    void run() System.out.println("running safely with 100kmph");    public static void main(String args[])     Honda honda= new Honda();   honda.run();      }   Output: Compile Time Error

78 Java final class If you make any class as final, you cannot extend it.
Example of final class final class Bike{}    class Honda extends Bike {      void run() { System.out.println("running safely with 100kmph"); }      public static void main(String args[])   Honda honda= new Honda();     honda.run();      }   Output: Compile Time Error

79 Abstract class in Java A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated. Example abstract class abstract class A{}  

80 abstract method A method that is declared as abstract and does not have implementation is known as abstract method. Example abstract method abstract void printStatus();

81 Example of abstract class that has abstract method
abstract class Bike { abstract void run(); } class Honda extends Bike void run() { System.out.println("running safely.."); public static void main(String args[]) Bike obj = new Honda(); obj.run(); Output: running safely..

82 Java static keyword The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class. The static can be: variable (also known as class variable) method (also known as class method)

83 Java static variable If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects e.g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading.

84 Java static method If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.

85 Example of static variable & method
class Student { int rlno; String name; static String clg = “MMP"; static void change() clg = ”MMPoly”; } Student(int r, String n) rlno = r; name = n; } void display () { System.out.println(rlno+" "+name+" "+clg); }   public static void main(String args[]) {        Student.change();           Student s1 = new Student (1,"Karan");  Student s2 = new Student(2,"Ayan");      Student s3 = new Student(3,"Suraj");       s1.display();       s2.display();       s3.display();     }   }   Output: 1 Karan MMPoly 2 Aryan MMPoly 3 Suraj MMPoly


Download ppt "Chapter No. 2 Classes, Objects & Methods"

Similar presentations


Ads by Google