1 / 24

Chapter 5

Chapter 5. Feb 08, 2008. Chapter 5. 1. Methods in a class are invoked using objects A a1 = new A(); a1.func1(); Calling object and the dot can be omitted if the method is called within the same class. func1(); //same as this.func1() ‏. Chapter 5. 2. null Constant.

Download Presentation

Chapter 5

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 5 Feb 08, 2008 Chapter 5 1

  2. Methods in a class are invoked using objects • A a1 = new A(); • a1.func1(); • Calling object and the dot can be omitted if the method is called within the same class. • func1(); //same as this.func1()‏ Chapter 5 2

  3. nullConstant • Indicates that the object reference variable does not reference any object. • Person p1 = null; • vs • Person p1 = new Person(“John”); • A null object can not invoke any methods • Results in a NullPointerException if used to invoke methods. • null corresponds to a reference address and hence use == or != to compare instead of 'equals' method. (“equals” compares the contents of two objects)‏ Chapter 5 3

  4. Static Variables • Also referred to as class variables. Accessed using the class name instead of object. • Used primarily to store information common to all the instances of a class. • Another common use of static variables is to define constants. • class Circle { • private static String • SHAPE = “round”; • public String getShape() { • return SHAPE; • } • } Circle c1 = new Circle(); Circle c2 = new Circle(); System.out.println(c1.getShape()); System.out.println(c2.getShape()); Chapter 5 4

  5. Static Methods • Static methods are members of the class but do not need to be invoked through objects of the class. They can be accessed using the class name. • Cannot access any non-static method or variable. • Example : java.lang.Math.pow(x, y); • Signature: • public static return_type method_name (parameters) ; • Invocation: • Class_name.method_name(parameters); Chapter 5 5

  6. Static Variables & Methods public class Champion { public String studentName; public static int numStudentsInGrp = 0; // to share info public static final String grpNickName = “Champs”; // usage as constant public Champion (String name){ studentName = name; numStudentsInGrp++; // tracks of number of members } public static String getGrpName (){ return grpNickName; } } Chapter 5 6

  7. Many Java library classes work with objects rather than primitives. • Example : Collection Classes (HashMap, ArrayList etc..,)‏ • Wrapper classes are used to convert a primitive data type to the corresponding class type. • Example: • Integer obj = new Integer(10); • int val = obj.intValue(); • Additionally, provides many utility methods • Examples: • Integer.parseInt(“10”, 16); • Integer.reverseBytes(10); Chapter 5 7

  8. Primitive to wrapper class conversion is called boxing. • Integer obj = new Integer(10); • Wrapper class to primitive type conversion is called unboxing • int val = obj.intValue(); • Java 5.0 performs boxing and unboxing automatically. • Integer obj = 10; • int val = obj; Chapter 5 8

  9. Use Wrapper classes to convert ‘string’ type to primitive datatypes. • Examples: • int i = Integer.parseInt(“50”); • float f = Float.parseFloat(“50.5”); • String to primitive conversions have to be done explicitly. • Recall the usage in JOptionPane example in Ch.2. Chapter 5

  10. toString() method can be used to convert primitives to String. Examples: • String s = Integer.toString(20); • String s1 = Float.toString(30.3); • The conversion from primitives to String is done implicitly. • Recall the example: • int numOfEggs = 10; • System.out.println(“The number of eggs is “+ numOfEggs ); • instead of • System.out.println(“The number of eggs is “ + Integer.toString(“numOfEggs”); Chapter 5

  11. Use the top down approach to design your task. • The collection of small tasks work together to accomplish a bigger task. • This approach is also called divide and conquer. • Example: Adding two complex numbers • class Complex { • public int real; • public int img; • public Complex(int real, int img) { • this.real = real; • this.img = img; • } • public Complex add (Complex c1, Complex c2) { • int r = addReal(c1, c2); • int i = addImg(c1, c2); • return new Complex (r, i); • } • public addReal(complex c1, complex c2) { return c1.real + c2.real; } • public addImg(complex c1, complex c2) { return c1.img + c2.img; } • } Chapter 5

  12. Bottom-up Testing : func1() invokes func2() : Test func2() completely before testing func1() Advantage : Suppose func1() testing gives incorrect results. It could mean a wrong piece of code either in func1() or in func2() or both. If func2() was tested earlier , we could have concluded that the wrong piece of code was in func1() alone. Chapter 5

  13. 2) Top-down testing using stubs : Stub is a simplified version of a method. Example: class Complex { public int real; public int img; public Complex(int real, int img) { this.real = real; this.img = img; } public Complex add (Complex c1, Complex c2) { int r = addReal(c1, c2); int I = addImg(c1, c2); return new Complex (r, i); } // Return expected values from the methods instead of having the actual code public addReal(complex c1,complex c2) {return x;} // stub for addReal public addImg(complex c1,complex c2) { return y;} // stub for addImg } Chapter 5

  14. Two or more methods of the same class can have the same name provided they differ in the parameters list. • This provision is known as overloading. • Overloading can be done on static, non-static methods as well as methods which do/do not return a value. • Examples: • 1) Complex.add(c1,c2); • Complex.add(c1.real, c2.real); • 2) System.out.println(“Hello!!”); • System.out.println(24); Chapter 5

  15. Should not differ in return type or variable names alone. • public class MyClass{ • public double add (int a , int b) ; • public double add (int c, int d); // Both cannot co-exist • public double add (int a, int b); • public int add(int a, int b); // Both cannot co-exist • } • double sum = MyClass.add(1,2); // Both the methods are applicable Chapter 5

  16. Automatic type conversion of arguments are done to match with one of the signatures. Example: public void add (Complex a, Complex b); public void add (double c, double d); //public void add (double a, int b) //Can it co-exist ? double d1 = 1.5; int d2 = 2; MyClass.add(d1,d2); // Calls the second method. Chapter 5

  17. When an instance of a class is created, a special method Constructor is called. Class_Name Object_Name = new Class_Name (Parameter(s)); • Constructor returns the reference to the new object created. • Like methods, constructors can have parameters • Used to initialize class variables, set up anything else necessary • Different constructors may initialize object to different values • No return type (do not even specify ‘void’)‏ • Examples: • public Classname ( <parameters_optional>)‏ Chapter 5

  18. Java provides a default constructor if no constructors are defined in the class. • You are not provided with the default constructor if there is a constructor (with parameters) already defined. • Use copy constructors to make a copy of an object • Class A { • int val ; • public A()‏ • { val = 10; } • public A(A a1) { • val = a1.val; • } • } A a1 = new A(); A a2 = a1; A a3 = new A(a1); What is the difference between a2 and a3 ? Chapter 5

  19. Calls to other methods in the constructor is common. • In general, the initializations to be done in the constructor can be done by invoking mutators. • Avoids repetition of code at times. • Class Circle { • int radius; • Public Circle(int r){ • if (r < 0 ) { • System.out. • println(“Invalid input”); • System.exit(0); • } • radius =r ; • } • public void setRadius(int r){ • if (r < 0) { • System.out. • println(“Invalid input”); • System.exit(0); • } • radius = r; • } • } Class Circle { int radius; Public Circle(int r){ setRadius(r); } public void setRadius(int r){ if (r < 0) { System.out.println(“Invalid input”); System.exit(0); } radius = r; } } Chapter 5

  20. A package groups and names a collection of related classes. • Usage : • package <package_name>; // This is the first line in the class. • The package name is a relative path name that assumes you start in a class path base directory and follow the path of subdirectories given by the package name. • example class path base directory: \javastuff\libraries • example package classes \javastuff\libraries\general\utilities Chapter 5

  21. Chapter 5

  22. A program or class definition can use all the classes in a package by placing a suitable import statement at the start of the file containing the program or class definition. import Package_Name; • - This is sufficient even if the program or class definition is not in the same directory as the classes in the package. Chapter 5

  23. Packages can help deal with name clashes which are situations in which two classes have the same name. • Ambiguities can be resolved by using the package name. • examples mystuff.CoolClass object1; yourstuff.CoolClass object2; Chapter 5

  24. Point out the errors in the following if any: Public class Circle { public static final double PI = 3.14; public double radius; public Circle (int r) { radius = r;} public static double getArea () { return PI*radius*radius; } } Public class MyClass { int var1; int var2; public MyClass (int a , int b) { var1 = a; var2 = b; } public MyClass(int v1, int v2){ if (v1 < 0 || v2 < 0) System.exit(0); var1 = v1; var2 = v2; } } Chapter 5

More Related