1 / 18

Classes & Objects

Classes & Objects. For learning java, you are not supposed to have a perfect definition of class and object. Put in simple words, a class is analogous to the plan of a building and its object to the building itself after it has been built. We’ll keep our vigil on the following matters…

akina
Télécharger la présentation

Classes & Objects

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. Classes & Objects For learning java, you are not supposed to have a perfect definition of class and object. Put in simple words, a class is analogous to the plan of a building and its object to the building itself after it has been built. We’ll keep our vigil on the following matters… • How the memory allocation takes place in runtime. • Instance member data and methods • Class data member and methods • Using “this” keyword and local variable suppressor. • Returning an object from a method • Passing object(s) as arguments to a method. sohamsengupta@yahoo.com

  2. Memory Allocation • It’s note worthy that all the memory allocation takes place in run time only and only when the class in loaded in the memory. Loading of classes at runtime will be discussed later on. • All the non-static data (variables and constants) are allocated memory individually for each object that is created. These are known as Instance data member. • All static data are allocated memory only once when the class is loaded in the memory. These are shared among all the objects of the class. They are known as class data member. • Methods, static or non-static are shared among objects and allocated into memory only once. • Static methods are allocated into memory only once when the class is loaded into memory • Non-static methods are allocated memory only once when the first object of the class is instantiated. sohamsengupta@yahoo.com

  3. Instantiating an Object • Roughly speaking, suppose we have a class MyClass and we want to instantiate and object obj of this type. declaration syntax would be, MyClass obj=new MyClass(); Here new is the memory allocation operator. Below look at the class declaration: class MyClass { int x; static int y; void show(int marks){ x=marks; System.out.println(“Your score is ”+x); } static void printHello(){ System.out.println(“Hello to JIS”); } } sohamsengupta@yahoo.com

  4. We are writing 2 lines of codesMyClass obj1=new MyClass();MyClass obj2=new MyClass(); • When the first object obj1 is instantiated, the class is loaded prior to instantiation. So, the static data int y is allocated into memory and assigned the default value, which is, in this case, 0. Static method printHello() is also allocated into memory. Now int x is allocated for obj1 and is assigned the default value, 0 here. Also, the instance method void show(int) is allocated into memory. Quick view of MyClass • Now come to second line where obj2 is instantiated. Now only x for obj2 is assigned the default value for int , 0. Both the Methods are shared and also the static int y is shared. But x for obj1 is definitely different from x for obj2. • The data members are accessed as obj1.x and obj2.x and methods as obj1.show(719) and obj2.show(940) etc. • Remember, since static members, data or method, are allocated into memory before the object instantiation, they can be accessed both by class name and of course, by any object name. So, we can refer to y as MyClass.y and the static method as MyClass.printHello() sohamsengupta@yahoo.com

  5. Memory Allocation Diagram obj1 int x obj2 int x static int y static void printHello() void show(int) sohamsengupta@yahoo.com

  6. A Demo Program using MyClass MyClass obj1=new MyClass(); obj1.show(719); MyClass obj2=new MyClass(); obj2.show(940); MyClass.printHello(); System.out.println(MyClass.y); obj1.printHello(); obj2.y=89; sohamsengupta@yahoo.com

  7. “this” keyword: local data suppressor Look at the code snippet… class A { int x=940; int y=880; void show(){ int x=10; System.out.println(x); System.out.println(this.x); } } sohamsengupta@yahoo.com

  8. Look at the code snippet… class A { int x=940; int y=880; void show(){ int x=10; System.out.println(x); System.out.println(this.x); } } On the LHS, in show() method, the local variable x suppresses the instance variable x. the console text output will be 10 and 940. “this” keyword refers to the current object, i.e. the object that is invoking the method Experts say, whenever we are using instance data member, we should use them with this keyword to minimize the possibility of such silly suppression that might occur. “this” is a final keyword and can not be altered. “this” keyword: Local VariableSupressor sohamsengupta@yahoo.com

  9. class Complex{ int x; int y; void set(int x,int y){ this.x=x; this.y=y; } void show(){ System.out.println(this.x+ “ + j* ”+this.y); } Complex add(Complex z){ Complex temp=new Complex(); temp.x=this.x+z.x; temp.y=this.y+z.y; return temp; } } public static void main(String[] args){ Complex z1=new Complex();// 1 z1.set(2,6); // 2 Complex z2=new Complex(); // 3 z2.set(7,16); // 4 Complex r=z1.add(z2); // 5 r.show(); // 6 } After Line No. Result z1.x=0, z1.y=0 z1.x=2, z1,y-6 z2.x =0, z2.y=0 z2.x=7, z2,y=16 r.x=9, r.y=22 (z=z2 & z1=this) 9 + j* 22 A demo program that returns an ObjectWe are trying to add two complex numbers. sohamsengupta@yahoo.com

  10. Java does not support call by reference; it supports only call by value. Some authors have misled this. If you pass primitive data as argument, the changes made inside the method are not reflected outside the method. But wait! If you pass an object as an argument the changes made to its data members are visible outside the method. Lo! Doesn’t it prove it’s call by reference? No way my friends! It doesn’t prove it. If you were to make the change to the object itself, the change would not be reflected outside the method. Even if you write a program to swap 2 objects of same class by passing them to a method, they won’t be swapped. Since arrays are objects, the same words apply to them. However, wise people speak less do more! Passing objects as arguments of methods sohamsengupta@yahoo.com

  11. class A { int x; void setX(int x){ this.x=x; } void show(){ System.out.println("The value of x is "+x); } } Output: Before change... The value of x is 90 After change... The value of x is 94 class G { static void change(A objA){ objA.setX(94); } public static void main(String[] args){ A objA=new A(); objA.setX(90); System.out.println("Before change..."); objA.show(); change(objA); System.out.println("After change..."); objA.show(); } } A Simple Program taking an object as Argument to a Method sohamsengupta@yahoo.com

  12. class G { static void change(A objA){ objA=new A(); objA.setX(67); } public static void main(String[] q){ A objA=new A(); objA.setX(90); System.out.println("Before change..."); objA.show(); change(objA); System.out.println("After change..."); objA.show(); } } Output: Before change... The value of x is 90 After change... The value of x is 90 So, it’s not at all a call by reference, but by value. We’ll just remember that primitive arguments are not changed but data members of object arguments change until the object itself does not change! Try your self the same thing with arrays So? There was a change in value. Now we want to change the object itself. So only change(A) is going to change only! sohamsengupta@yahoo.com

  13. class G { static void change(int[] a){ a[0]=12; } static void show(int[] a){ for(int i=0;i<a.length;i++){ System.out.println(a[i]); } } public static void main(String[]s){ int[] x={1,2,3,4}; show(x); change(x); show(x); } } Output: 1 2 3 4 12 2 3 Now if we just modify the method change(int[]) as a=new int[78]; The output will be: 1 2 3 4 1 2 3 4 Passing arrays as arguments to a method sohamsengupta@yahoo.com

  14. More on Methods • Static methods can access only static data member & invoke only static methods. • Methods must have a return type either void or any primitive type or a Reference Type (i.e. an Object). • Methods with return type void can have return statements. • main(String[] args) is declared static because it’s the method which JVM calls after loading the class say A, followed by execution of the command java A. At that time no object is available, so it must be static and JVM calls it as A.main(String[] d). One more thing on main method. The argument String[]args can be any valid variable name that is not defined inside the main method itself. Actually it’s the command line argument. CONTD. sohamsengupta@yahoo.com

  15. More on Method (CONTD.) 5. Methods can be overloaded by keeping the method name same but making the argument differ in that (a) Number of arguments different (b) Types of arguments different (c) The sequence in which they appear different Method overloading is irrespective of return type 6. Method overloading is known as Compile Time Polymorphism. Why is Compile time? Is there any proof? Yes friends! I do have an excellent proof which is hitherto beyond your scope. That’ll be discussed in right time. 7. We shall now see some examples of method overloading but before that we’ll have look at Command line arguments of the main(String[] soham) method sohamsengupta@yahoo.com

  16. class A { public static void main(String[] t){ System.out.println(“There r ”+t.length+ “Command Line args”); for(int k=0;k<t.length;k++){ System.out.println("args["+k+"]"+"\t"+t[k]); } } } >java A > java A I am an Indian First run will output… There are 0 Command Line args 2nd run will output… There are 4 Command Line args args[0] I args[1] am args[2] an args[3] Indian So, the entire CLA is delimited by white spaces and then put into String Array(String[]) It’s useful when there is not much involvement of a GUI driven system. Command Line Arguments sohamsengupta@yahoo.com

  17. class A { void show(){ for(int i=1;i<=10;i++){ System.out.println(“@”); } } void show(int n){ for(int i=1;i<=n;i++){ System.out.println(“@”); } } void show(int n, char ch){ for(int i=1;i<=n;i++){ System.out.println(ch); } } } The first method prints “@” 10 times The 2nd method does n times taken as argument The 3rd method prints char ch, n times both taken as argument. Method overloading is useful for large development with most of the Java Design Patterns and it saves the developer from giving and remembering names of method that do similar job. Example of Method Overloading sohamsengupta@yahoo.com

  18. class T { static void show(int x,double y){ } static void show(double y,int x){ } public static void main(String[] ar){ show(10,20); } } Here overloading id done by changing the order in which the args appear. Up to this is OK. But when you call it as show(10,20) compiler can’t make out which one you are intending to call. So compile time error occurs referring to the ambiguity. The above indirectly and logically proves overloading is compile time event. When Method Overloading is Irrational sohamsengupta@yahoo.com

More Related