Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 (part 2) Khalid Siddiqui.

Slides:



Advertisements
Similar presentations
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Chapter 3 Introduction to Classes, Objects, Methods, and Strings
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Road Map Introduction to object oriented programming. Classes
Terms and Rules Professor Evan Korth New York University (All rights reserved)
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
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.
LESSON 2 CREATING A JAVA APPLICATION JAVA PROGRAMMING Compiled By: Edwin O. Okech [Tutor, Amoud University]
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.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Objects and Classes Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary.
Java Syntax and Style JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
Data Types, Variables, and Arithmetic JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Chapter 4 Introduction to Classes, Objects, Methods and strings
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Inheritance A Review of Objects, Classes, and Subclasses.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes and Objects Including inheritance. OOP — Object-Oriented Programming In OOP system, the class is a fundamental unit. An OOP program models a.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Why Use Classes - Anatomy of a Class.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
AP Computer Science A – Healdsburg High School 1 static Keyword in Java - Static variables - Static methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Objects and Classes Start on Slide 30 for day 2 Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Much of.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
1 Class and Object Lecture 7. 2 Classes Classes are constructs that define objects of the same type. A Java class uses instance variables to define data.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
AP Computer Science A – Healdsburg High School 1 Unit 9 - Parameter Passing in Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
Console Input and Output JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin,
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
The Essentials of a Java Program JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Topic: Classes and Objects
Java Programming: Guided Learning with Early Objects
3 Introduction to Classes and Objects.
Java Classes, Objects, and Events: A Preview
Methods Chapter 6.
Chapter 3: Using Methods, Classes, and Objects
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Java Methods Objects and Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 6 Methods: A Deeper Look
Java Methods Objects and Classes Start on Slide 30 for day 2
Java Methods Objects and Classes Start on Slide 30 for day 2
Object Oriented Programming in java
Java Programming Language
Corresponds with Chapter 5
Presentation transcript:

Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 (part 2) Khalid Siddiqui

Objectives Get an introduction to classes, objects, fields, constructors, and methods; get a general idea of how a small program is put together Get a feel for how methods call each other; learn about private and public methods Learn defining and calling methods and constructors

Objectives (Contd.): Learn how arguments are passed to methods and constructors and how to return values from methods Learn about static (class) and non-static (instance) fields and methods

Methods To define a method: –decide between public and private (usually public) –give it a name –specify the types of arguments (formal parameters) and give them names –specify the method’s return type or chose void –write the method’s code public [or private] returnType methodName (type1 name1,..., typeN nameN) {... } Header Body

Methods (cont’d) A method is always defined inside a class. A method returns a value of the specified type unless it is declared void; the return type can be any primitive data type or a class type. A method’s arguments can be of any primitive data types or class types. public [or private] returnType methodName ( ) {... } Empty parentheses indicate that a method takes no arguments.

Methods: Java Style Method names start with lowercase letters. Method names usually sound like verbs. The name of a method that returns the value of a field often starts with get: getWidth, getX The name of a method that sets the value of a field often starts with set: setLocation, setText

Overloaded Methods Methods of the same class that have the same name but different numbers or types of arguments are called overloaded methods. Use overloaded methods when they perform similar tasks: public void move (int x, int y) {... } public void move (double x, double y) {... } public void move (Point p) {... } public Fraction add (int n) {... } public Fraction add (Fraction other) {... }

Overloaded Methods (cont’d) The compiler treats overloaded methods as completely different methods. The compiler knows which one to call based on the number and the types of the arguments: Circle circle = new Circle(5); circle.move (50, 100);... Point center = new Point(50, 100); circle.move (center);... public class Circle {... public void move (int x, int y) {... } public void move (Point p) {... }... }

Constructors A constructor is like a method for creating objects of the class. A constructor often initializes an object’s fields. Constructors do not have a return type (not even void) and they do not return a value. All constructors in a class have the same name — the name of the class. Constructors may take arguments.

Constructors (cont’d) If a class has more than one constructor, they are “overloaded” and must have different numbers and/or types of arguments. Programmers often provide a “no-args” constructor that takes no arguments. If a programmer does not define any constructors, Java provides one default no-args constructor, which allocates memory and sets fields to the default values.

Constructors (cont’d) public class Fraction { private int num, denom; public Fraction ( ) { num = 0; denom = 1; } public Fraction (int n) { num = n; denom = 1; } Continued   public Fraction (int p, int q) { num = p; denom = q; reduce (); } public Fraction (Fraction other) { num = other.num; denom = other.denom; }... } “No-args” constructor Copy constructor

Constructors (cont’d) Constructors of a class can call each other using the keyword this — a good way to avoid duplicating code:... public Fraction (int p, int q) { num = p; denom = q; reduce (); }... public class Fraction {... public Fraction (int n) { this (n, 1); }...

Operator new Constructors are invoked using new Fraction f1 = new Fraction ( ); Fraction f2 = new Fraction (5); Fraction f3 = new Fraction (4, 6); Fraction f4 = new Fraction (f3); 0 / 1 5 / 1 2 / 3

Operator new (cont’d) You must create an object before you can use it; the new operator is a way to do it Fraction f; f= n ew Fraction (2, 3); f = new Fraction (3, 4); f is set to null Now f refers to a valid object Now f refers to another object (the old object is “garbage- collected”)

Static Fields A static field (a.k.a. class field or class variable) is shared by all objects of the class. A static field can hold a constant shared by all objects of the class: A non-static field (a.k.a. instance field or instance variable) belongs to an individual object. public class RollingDie { private static final double slowDown = 0.97; private static final double speedFactor = 0.04;... Reserved words: static final

Static Fields (cont’d) Static fields are stored with the class code, separately from non-static fields that describe an individual object. Public static fields, usually global constants, are referred to in other classes using “dot notation”: ClassName. constName double area = Math.PI * r * r; setBackground(Color.blue); c.add(btn, BorderLayout.NORTH); System.out.println(area);

Static Fields (cont’d) Usually static fields are NOT initialized in constructors (they are initialized either in declarations or in public static methods). If a class has only static fields and does not have any non-static (instance) fields, there is no point in creating objects of that class (all of them would be identical). Math and System are examples of the above. In fact, they have no public constructors and cannot be instantiated.

Static Methods Static methods can access and manipulate a class’s static fields. Static methods cannot access non-static fields or call non-static methods of the class. Static methods are called using “dot notation”: ClassName. statMethod(...) double x = Math. random(); double y = Math. sqrt (x); System. exit();

Instance Methods Non-static methods are also called instance methods. An instance method is called for a particular object using “dot notation”: objName. instMethod(...); Instance methods can access ALL fields and call ALL methods of their class — both class and instance fields and methods.

Static (Class) vs. Non-Static (Instance) public class MyClass { public static final int statConst; private static int statVar; private int instVar;... public static int statMethod(...) { statVar = statConst; statMethod2(...); instVar =...; instMethod(...); } Continued   public int instMethod(...) { statVar = statConst; inst Var = statConst; instVar = statMethod(...); statVar = instMethod2(...);... } public int instMethod2(...) {... }... } Error! OK All OK

Static vs. Non-Static (cont’d) Note: main is static and therefore cannot access non-static fields or call non-static methods of its class: public class Hello { private String message = "Hello, World"; public static void main (String[ ] args) { System.out.println (message); } Error: non-static variable message is used in static context (main)

Passing Arguments to Constructors and Methods Any expression that has an appropriate data type can serve as an argument: double a = 3, b = - 4;... Polynomial p = new Polynomial(1.0, - (a + b), a * b);... double y = p.getValue ( 2 * b - a);

Passing Arguments (cont’d) int is promoted to double when necessary: A “smaller” type can be promoted to a “larger” type (e.g., int to long, float to double). The same as: ( 3.0 )... Polynomial p = new Polynomial (1, - 5, 6); double y = p.getValue ( 3 ); The same as: (1.0, -5.0, 6.0)

Passing Arguments (cont’d) Primitive data types are always passed “by value”: the value is copied into the parameter. double x = 3.0; double y = p.getValue ( x ); public class Polynomial {... public double getValue (double u) { double v;... } x: 3.0 y: u: 3.0 v: copy u acts like a local variable in getValue

Passing Arguments (cont’d) The original argument remains unchanged: public class MyMath {... public double square (double x) { x *= x; return x; } MyMath calc = new MyMath(); double x = 3.0; double y = calc.square (x); System.out.println (x + " " + y); the original x is unchanged. Output: 3 9 x here is a copy of the argument. The copy is changed, but...

Passing Objects as Arguments Objects are always passed as references: the address is copied, not the object. Fraction f1 = new Fraction (1, 2); Fraction f2 = new Fraction (5, 17); Fraction f3 = f1.add (f2); public class Fraction {... public Fraction add (Fraction f) { Fraction sum;... } f2: addr2 f: addr2 sum: copy 5/17 f1: addr1

A method can change an object passed to it as an argument (because the method gets a reference to the original object). A method can change the object for which it was called (this object acts like an implicit argument): Passing Objects as Arguments (cont’d) panel.setBackround(Color.green);

Inside a method, this refers to the object for which the method was called. this can be passed to other constructors and methods as an argument: Passing Objects as Arguments (cont’d) public class ChessGame {... Player player1 = new Player (this);...

return A method, unless void, returns a value of the specified type to the calling method. The return statement is used to immediately quit the method and return a value: return expression; The type of the return value or expression must match the method’s declared return type.

return (cont’d) A method can have several return statements; then all but one of them must be inside an if or else (or in a switch): public someType myMethod (...) {... if (...) return ; else return ;... return ; }

return (cont’d) A boolean method can return true, false, or the result of a boolean expression: public boolean myMethod (...) {... if (...) return true;... return n % 2 == 0; }

return (cont’d) A void method can use a return statement to quit the method early: public void myMethod (...) {... if (...) return;... } No need for a redundant return at the end

return (cont’d) If its return type is a class, the method returns a reference to an object (or null). Often the returned object is created in the method using new. For example: The returned object can also come from the arguments or from calls to other methods. public Fraction inverse () { if (num == 0) return null; return new Fraction (denom, num); }

Encapsulation Hiding the implementation details of a class (making all fields and helper methods private) is called encapsulation. Encapsulation helps in program maintenance and team development. A class encapsulates a small set of well- defined tasks that objects of a class can perform.

8-35 public vs. private Public constructors and methods of a class constitute its interface with classes that use it — its clients. All fields are usually declared private — they are hidden from clients. Static constants occasionally may be public. “Helper” methods that are needed only inside the class are declared private.

public vs. private (cont’d) public class MyClass { // Constructors: public MyClass (...) {... }... // Public methods: public myMethod (...) {... }... // Private methods: private myMethod (...) {... }... // Private fields: private myField;... }

8-37 public vs. private (cont’d) A private field is open not just within the object but to the entire class; any object of the same class can access or even modify it. public class Fraction { private int num, denom;... public multiply (Fraction other) { int newNum = num * other. num;... }

Accessors and Modifiers A programmer often provides methods, called accessors, that return values of private fields; methods that set values of private fields are called modifiers. Accessors’ names often start with get, and modifiers’ names often start with set. These are not precise categories: the same method can modify several fields or modify a field and also return its old or new value.

Files and Folders javac automatically looks for classes (.java or.class files) in the current folder, or, if classpath is set, in folders listed in the classpath string. A missing file may be reported as a syntax error when compiling another file. If you set classpath, include the current folder. It is denoted by a dot. For example:.; C:\javamethods\EasyIO IDE helps take care of the file locations.

Libraries Java programs are usually not written from scratch. There are hundreds of library classes for all occasions. Library classes are organized into packages. For example: java.util — miscellaneous utility classes java.awt — windowing and graphics toolkit javax.swing — newer GUI package Swing

import Full library class names include the package name. For example: java.awt.Color javax.swing.JButton import statements at the top of your program let you refer to library classes by their short names: import javax.swing. JButton ;... JButton go = new JButton ("Click here"); Fully-qualified name

import (cont’d) You can import names for all the classes in a package by using a wildcard. * : import java.awt.* ; import java.awt.event.* ; import javax.swing.* ; java.lang is imported automatically into all classes; defines System, Math, Object, String, and other commonly used classes. Imports all classes from awt, awt.event, and swing packages

public class SomeClass { Fields Constructors Methods } private: visible only inside this class public: visible in other classes Attributes / variables that define the object’s state. Can hold numbers, characters, strings, other objects. Usually private. Code for constructing a new object and initializing its fields. Usually public. Actions that an object can take. Can be public or private.

public class FallingCube { private final int cubeSize; private int cubeX, cubeY; // Cube coordinates... private char randomLetter; // Cube letter public FallingCube(int size) { cubeSize = size;... } public void start() { cubeX = 0; cubeY = -cubeSize;... }... } Fields Constructor Methods The name of a constructor is always the same as the name of the class.

private (or public) [static] [final] datatype name ; Fields Usually private May be present: means the field is shared by all objects in the class May be present: means the field is a constant int, double, etc., or an object: String, JButton, FallingCube, Timer You name it!

Fields (cont’d) May have primitive data types: int, char, double, etc. private int cubeX, cubeY; // cube coordinates... private char randomLetter; // cube letter

Fields (cont’d) May be objects of different types: private FallingCube cube ; private Timer t ; private static final String letters ;

Constructors Constructors are like methods for creating objects of a class. Most constructors initialize the object’s fields. Constructors may take parameters. A class may have several constructors that differ in the number or types of their parameters. All of a class’s constructors have the same name as the class.

Constructors (cont’d) go = new JButton("Go");

Constructors (cont’d) Call them using the new operator: cube = new FallingCube (CUBESIZE);... t = new Timer (delay, this) Calls FallingCube ’s constructor with CUBESIZE as the parameter Calls Timer ’s constructor with delay and this (i.e. this object) as the parameters (see Java docs for javax.swing.Timer )

Methods Call them for a particular object: cube.start(); whiteboard.dropCube(); randomLetter = letters.charAt(i); But call static (“class”) methods for the whole class, not a specific object: y = Math.sqrt (x);

Methods (cont’d) Constructors and methods can call other public and private methods of the same class. Constructors and methods can call only public methods of another class. Class X private method Class Y public method

Methods (cont’d) You can call methods with specific arguments: g.drawRect (75, 25, 150, 50); g.drawString ("Welcome", 120, 50); The number and types of arguments must match the method’s parameters: public void drawRect ( int x, int y, int width, int height ) {...} public void drawString ( String msg, int x, int y ) {...}