Chapter 5. Feb 08, Chapter 5 1

Similar documents
More About Objects and Methods. Objectives. Outline. Chapter 6

More About Objects and Methods

More About Objects and Methods

More About Objects and Methods. Objectives. Outline. Harald Gall, Prof. Dr. Institut für Informatik Universität Zürich.

More About Objects and Methods

More About Objects and Methods

More About Objects and Methods

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Chapter 4 Defining Classes I

CSC Java Programming, Fall Java Data Types and Control Constructs

Chapter 4. Defining Classes I

Programming - 2. Common Errors

Computer Science II (20073) Week 1: Review and Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Computer Science II (20082) Week 1: Review and Inheritance

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

CS180 Recitation. More about Objects and Methods

CS 2530 INTERMEDIATE COMPUTING

Chapter 5. Defining Classes II. Slides prepared by Rose Williams, Binghamton University

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Practice Questions for Chapter 9

CH. 2 OBJECT-ORIENTED PROGRAMMING

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

Anatomy of a Class Encapsulation Anatomy of a Method

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Inf1-OOP. Data Types. Defining Data Types in Java. type value set operations. Overview. Circle Class. Creating Data Types 1.

Language Features. 1. The primitive types int, double, and boolean are part of the AP

1B1b Classes in Java Part I

Chapter 7 User-Defined Methods. Chapter Objectives

Introduction to Programming Using Java (98-388)

CS1083 Week 2: Arrays, ArrayList

In Java there are three types of data values:

Recharge (int, int, int); //constructor declared void disply();

Methods Common to all Classes

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Appendix: Common Errors

Chapter 4. Defining Classes I

Chapter 4: Writing Classes

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

Chapter 5. Defining Classes II. Copyright 2016 Pearson Inc. All rights reserved.

Class 9: Static Methods and Data Members

OBJECT ORİENTATİON ENCAPSULATİON

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Recitation 02/02/07 Defining Classes and Methods. Chapter 4

Java Object Oriented Design. CSC207 Fall 2014

More About Objects and Methods

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

EECS168 Exam 3 Review

JAVA GUI PROGRAMMING REVISION TOUR III

Object Oriented Programming COP3330 / CGS5409

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

UMBC CMSC 331 Final Exam

CLASS DESIGN. Objectives MODULE 4

Chapter 3 Function Overloading

Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park

ECOM 2324 COMPUTER PROGRAMMING II

CS111: PROGRAMMING LANGUAGE II

Lecture 5: Methods CS2301

Object Oriented Methods : Deeper Look Lecture Three

PIC 20A The Basics of Java

Programming overview

Distributed Systems Recitation 1. Tamim Jabban

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chapter 5: Classes and Objects in Depth. Introduction to methods

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

BBM 102 Introduction to Programming II Spring 2017

CMSC 132: Object-Oriented Programming II

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

University of Palestine. Mid Exam Total Grade: 100

Use the scantron sheet to enter the answer to questions (pages 1-6)

PIC 20A Number, Autoboxing, and Unboxing

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Defining Classes and Methods

F I N A L E X A M I N A T I O N

Defining Classes and Methods

Selected Questions from by Nageshwara Rao

11/19/2014. Objects. Chapter 4: Writing Classes. Classes. Writing Classes. Java Software Solutions for AP* Computer Science A 2nd Edition

CSC 1351 The Twelve Hour Exam From Hell

Chapter 2: Using Data

Class, Variable, Constructor, Object, Method Questions

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Documenting, Using, and Testing Utility Classes

Week 6: Review. Java is Case Sensitive

OBJECT ORIENTED PROGRAMMING USING C++

Inheritance and Polymorphism

Addendum File Web Design and Development (CS506)

CS110D: PROGRAMMING LANGUAGE I

ITI Introduction to Computing II

CS171:Introduction to Computer Science II

The Basic Parts of Java

Chapter 14 Abstract Classes and Interfaces

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Topic 7: Algebraic Data Types

Programming in the Large II: Objects and Classes (Part 1)

Transcription:

Feb 08, 2008 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() 2

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) 3

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()); 4

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); 5

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; 6

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

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; 8

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.

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

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;

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.

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

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

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 coexist double sum = MyClass.add(1,2); // Both the methods are applicable

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 coexist? double d1 = 1.5; int d2 = 2; MyClass.add(d1,d2); // Calls the second method.

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 ( <parameters_optional>)

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?

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;

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

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.

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;

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