Chapter 51 Feb 08, 2008. Chapter 52  Methods in a class are invoked using objects A a1 = new A(); a1.func1();  Calling object and the dot can be omitted.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Java Software Solutions
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Chapter 51 More About Objects and Methods Chapter 5.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
More About Objects and Methods
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction To Scientific Programming Chapter 5 – More About Objects and Methods.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 8. About the Midterm Exam.. Exam on March 12 Monday (Tentatively) Review on March 7 Wednesday Cover from Chapter 6 Grades will be out before spring.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Static Methods and Static Variables.
Chapter 51 More About Objects and Methods Chapter 5.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part C Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
More on Objects Mehdi Einali Advanced Programming in Java 1.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Java Classes Introduction. Contents Introduction Objects and Classes Using the Methods in a Java Class – References and Aliases Defining a Java Class.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Functions + Overloading + Scope
More About Objects and Methods
Topic: Classes and Objects
Static Members and Methods
Java Programming: Guided Learning with Early Objects
Java Primer 1: Types, Classes and Operators
More About Objects and Methods
CMSC 202 Static Methods.
CSC240 Computer Science III
Defining Classes II.
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
More About Objects and Methods
More About Objects and Methods
Classes and Objects Static Methods
Java Programming Language
Classes, Objects and Methods
More About Objects and Methods Chapter 5 Programming with Methods
Chapter 7 Objects and Classes
More About Objects and Methods Chapter 5 Programming with Methods
Presentation transcript:

Chapter 51 Feb 08, 2008

Chapter 52  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 53 null Constant 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 54  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()); Static Variables

Chapter 55 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); Static Methods

Chapter 56 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; } Static Variables & Methods

Chapter 57  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 58  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 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 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 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 1)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 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 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 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 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 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 i.Used to initialize class variables, set up anything else necessary ii.Different constructors may initialize object to different values No return type (do not even specify ‘void’)‏ Examples: public Classname ( )‏

Chapter 5 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 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 A package groups and names a collection of related classes. Usage : package ; // 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

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 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 1.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; } 1.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; } Point out the errors in the following if any: