1 / 85

Chapter No. 2 Classes, Objects & Methods

This chapter explains the concept of classes, objects, and methods in Java programming. It covers topics such as defining a class, creating objects, constructors, method overloading, and more.

rjeanpierre
Download Presentation

Chapter No. 2 Classes, Objects & Methods

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. Chapter No. 2Classes, 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: classclass_name { field declaration; method declaration; }  

  4. Object • Anobject 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{   intid=1; //field or data member or instance variable    String name=“ABC”; publicstaticvoid 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(inti,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. publicstaticvoid main(String args[]) {     Student s1 = new Student(111,"Karan");       Student s2 = new Student(222,"Aryan",25);       s1.display();       s2.display();      }   }   class Student {   int id;       String name;   int age;       Student(inti,String n) {       id = i;       name = n;       }       Student(inti,Stringn,int a) {       id = i;       name = n;       age=a;       }   void display() { System.out.println(id+" "+name+" "+age); }  

  12. Method Overloading in Java • A Java method is a collection of statements that are grouped together to perform an operation. • Creating Method modifier returnTypenameOfMethod (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(inta,long b) { System.out.println(a+b); }   void sum(inta,intb,int c) { System.out.println(a+b+c); } public static void main(String args[]) { Overloadingobj=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. 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_Methodsobj = new Nest_Methods(); intvol = obj.volume(l, b, h); System.out.println("Volume:"+vol); } } import java.util.Scanner; public class Nest_Methods { intarea(int l, int b) { intar = 6 * l * b; return ar; } intvolume(int l, int b, int h) { intar = area(l, b); System.out.println("Area:"+ar); intvol ; vol= l * b * h; return 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 TestThis2 {   public static void main(String args[]) {   Student s1=new Student(111,"ankit”);  Student s2=new Student(112,"sumit”);   s1.display();   s2.display();   } }   class Student { introllno;   String name;   Student(introllno,Stringname) { this.rollno=rollno;   this.name=name;    } void display() { System.out.println(rollno+" "+name); } }  

  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. publicclassCommandLine { public staticvoid main(Stringargs[]) { for(inti=0;i<args.length;i++) { System.out.println("args["+i+"]: "+args[i]); } } } executing this program as shown here − • D:\>javacCommandLine D:\>java CommandLine this is a command line 200 -100

  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-lengtharguments • The varargsallows 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_typemethod_name(data_type... variableName){}

  23. classVarargsExample { staticvoid display(String... values) { System.out.println("display method invoked ");   for(String s:values) { System.out.println(s);   } } publicstaticvoid main(String args[]) {    display();//zero argument     display("hello");//one argument    display("my","name","is","varargs");//four arguments   } }   Output: display method invoked display method invoked hello display method invoked 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. protectedvoid 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. Arrays & StringsTypes 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

  29. Syntax to Declare an Array in java dataTypearr[];   dataTypearrayRefVar[][];    • Instantiation of an Array in java arrayRefVar=newdatatype[size];   arrayRefVar[][]=newdatatype[size][size]; • We can declare, instantiate and initialize the java array together by: int a[]={33,3,4,5}; intarr[][]={{1,2,3},{2,4,5},{4,4,5}};  

  30. classTestarray { publicstaticvoid main(String args[]) { intarr[][]={{1,2,3},{2,4,5},{4,4,5}};   for(inti=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

  31. 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");

  32. publicclassStringExample { publicstaticvoid main(String args[]) { String s1="java“; charch[]={'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

  33. 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 ). • For example: • String str = "java"; • System.out.println(str.equalsIgnoreCase("JAVA")); • Output : true

  34. 3. indexOf()function returns the index of first occurrence of a substring or a character. Forms of indexOf() method: intindexOf(String str)It returns the index within this string of the first occurrence of the specified substring. intindexOf(String str, intfromIndex)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: 2 11 6 -1

  35. 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. For example: String str = "Change me"; System.out.println(str.replace('m','M')); Output : Change Me

  36. 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 = "0123456789"; System.out.println(str.substring(4)); Output : 456789 System.out.println(str.substring(4,7)); Output : 456

  37. 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. For Example: String str = "abcdef"; System.out.println(str.toUpperCase()); Output : ABCDEF

  38. 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. For example String str = " hello "; System.out.println(str.trim()); output : hello trim() method removes only the leading and trailing whitespaces.

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

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

  41. 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.eStringBuffer class is used when we have to make lot of modifications to our string.

  42. 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.  StringBufferstr = new StringBuffer("test"); str.append(123); System.out.println(str); Output : test123

  43. insert()This method inserts one string into another. Here are few forms of insert() method. • StringBufferinsert(int index, String str) • StringBufferinsert(int index, int num) • StringBufferinsert(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. StringBufferstr = new StringBuffer("test"); str.insert(4, 123); System.out.println(str); Output : test123

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

  45. 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(intnewLength) 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

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

  47. Difference between Vector & Array

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

  49. 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.  Syntax : vect_object.capacity(); Example : If v is the Vector object , v. capacity();

More Related