Enhancing classes Visibility modifiers and encapsulation revisited

Slides:



Advertisements
Similar presentations
Interfaces A Java interface is a collection
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Chapter 4: Writing Classes
Lecture 2: Object Oriented Programming I
Road Map Introduction to object oriented programming. Classes
Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Classes, Encapsulation, Methods and Constructors
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
INF 523Q Chapter 5: Enhancing Classes. 2 b We can now explore various aspects of classes and objects in more detail b Chapter 5 focuses on: object references.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
6-1 Object-Oriented Design Today we focuses on: –the this reference (Chapter 7) –the static modifier (Chapter 7) –method overloading (Chapter 7)
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
The Java Programming Language
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
C# Programming Methods.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Methods.
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
© 2004 Pearson Addison-Wesley. All rights reserved November 12, 2007 Inheritance ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Java 5 Class Anatomy. User Defined Classes To this point we’ve been using classes that have been defined in the Java standard class library. Creating.
Topic: Classes and Objects
Chapter 5: Enhancing Classes
Chapter 4: Writing Classes
Inheritance November 10, 2006 ComS 207: Programming I (in Java)
More Object Oriented Programming
Object Based Programming
Inheritance April 7, 2006 ComS 207: Programming I (in Java)
The this Reference The this reference allows an object to refer to itself That is, the this reference, used inside a method, refers to the object through.
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Object Oriented Programming
Static is one of the modifiers that determine variable and method characteristics. The static modifier associates a variable or method with its class.
Object Oriented Programming Review
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Presentation transcript:

Enhancing classes Visibility modifiers and encapsulation revisited syllabus Visibility modifiers and encapsulation revisited Static methods and variables Method/constructor overloading Nested classes basic programming concepts object oriented programming topics in computer science

Passing Objects to Methods Parameters in a Java method are passed by value: a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) Passing parameters is essentially an assignment Both primitive types and object references can be passed as parameters When an object is passed to a method, the actual parameter and the formal parameter become aliases

Example: Arrays as parameters static void setArrayEl(int[] arr, int i, int n){ arr[i] = n; } static void setEl(int el, int newVal){ el = newval; public static void main(String[] args){ int[] samples = {1,2,3,4,5,6}; setArrayEl(samples,1,0); setEl(samples[1],10);

Overloading Methods Method overloading is the process of using the same method name for multiple methods The signature of each overloaded method must be unique The signature includes the number, type, and order of the parameters; overloaded methods differ by the number and/or type of parameters they get. The compiler must be able to determine which version of the method is being invoked by analyzing the parameters The return type of the method is not part of the signature

Overloading Methods float tryMe (int x) { return x + .375; } Version 1 float tryMe (int x, float y) { return x*y; } Version 2 result = tryMe (25, 4.32) Invocation

Overloaded Methods The println method is overloaded: etc. println (String s) println (int i) println (double d) etc. The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

Constructor Overloading Constructors can be overloaded: An overloaded constructor provides multiple ways to set up a new object The overloaded constructors differ by the number and type of parameters they get. When we construct an object, the compiler decides which constructor to invoke according to the type of the actual parameters A constructor with no parameters is called a default constructor

// ------------------------------------------------ // Constructs a new clock with the specified hours, // minutes and seconds read. // If one of the paramenters is not in the allowed // range, the time will be reset to 00:00:00. // @param hours: the hours to be set (0-23) // @param minutes: the minutes to be set (0-59) // @param seconds: the seconds to be set (0-59) public Clock(int hours, int minutes, int seconds) { if ((seconds >= 0) && (seconds < 60) && (minutes >= 0) && (minutes < 60) && (hours >= 0) && (hours < 24)) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } else { this.hours = 0; this.minutes = 0; this.seconds = 0;

Overloading Constructors Clock c1 = new Clock(); // default constructor Clock c2 = new Clock(23,12,50); // Clock(int, int, int) constructor The constructor must always check the parameters: an object should not be initialized to an inconsistent state What is an inconsistent state in a clock?

Visibility Modifiers - Classes A class can be defined either with the public modifier or without a visibility modifier If a class is declared as public it can be used by any other class If a class is declared without a visibility modifier it has a default visibility; this draws a limit to which other classes can use this class Classes that define a new type of objects, that are supposed to be used anywhere, should be declared public

Any other class can use MyClass public MyClass { // … }

The Static Modifier, Container Class The static modifier can be applied to variables or methods It associates a variable or method with the class rather than an object Methods that are declared as static do not act upon any particular object; they just encapsulate a given task, a given algorithm Container class: we can write a class that is a collection of static methods; such a class is not meant to define a new type of object, it is just used as a library for utilities that are related in some way

Example - a Math Class // --------------------------------- // A library of mathematical methods public class Math { // ------------------------------------------- // Computes the trigonometric sine of an angle public static double sin(double x) { // ... } // ---------------------------------------- // Computes the logarithm of a given number public static double log(double x) {

Use of Static Methods When we call a static method we should specify the class to which method belongs. double x = Math.sin(alpha); int c = Math.max(a,b); double y = Math.random(); The main method is static; it is invoked by the system without creating an object If a static method calls another static method of the same class we can omit the class-name prefix

Static Variables A variable that is declared static is associated with the class itself and not with an instance of it Static variables are also called class variables We use static variables to store information that is not associated with a given object, but is relevant to the class We have already seen such usage - constants of a class (final static)

Static Variables - Example public class BankAccount { private long accountNumber; // serial number private float balance; // balance in dollars private static int numberOfAccounts = 0; public BankAccount() { this.accountNumber = numberOfAccounts; numberOfAccounts++; this.balance = 0; this.owner = “Smith”; } public static int getNumberOfAccounts { return numberOfAccounts;

Static Methods and Instance Variables cannot reference instance variables (i.e., access instance variable when an object doesn’t exist) can reference static variables or local variables (within the method) this has no meaning inside a static method, thus its use inside a static method is not allowed Instance methods can access both instance and static variables

Static Variables Normally, each object has its own data space If a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created as soon as the class in which it is declared is loaded All objects created from the class share access to the static variable Changing the value of a static variable in one object changes it for all others

Nested Classes In addition to a class containing data and methods, it can also contain other classes A class declared within another class is called a nested class Outer Class Nested Class

Nested Classes A nested class has access to the variables and methods of the outer class, even if they are declared private In certain situations this makes the implementation of the classes easier because they can easily share information Furthermore, the nested class can be protected by the outer class from external use

Nested Classes A nested class produces a separate bytecode file If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class Nested classes can be declared as static, in which case they cannot refer to instance variables or methods A nonstatic nested class is called an inner class

Example: a nested class // regular class definition public class Farm { private String country; // inner class definition private class Dog { public void makeSound() { if (country.equals("Israel")) System.out.println("how-how"); else System.out.println("woof-woof"); }

Writing code: division into methods Complicated tasks or tasks that occur often within a class should be wrapped in a method This results in a readable and manageable code This is very helpful when implementing algorithms, or when we need “helper” methods in classes

Division into Methods - Example // Prints all the prime numbers public class Primes { public static void main(String[] args) { int number = 0; while (true) { number = number + 1; if (isPrime(number)) System.out.println(number); }

Division into Methods - Example // Prints all the prime numbers public class Primes { public static void main(String[] args) { int number = 0; while (true) { number = number + 1; if (isPrime(number)) System.out.println(number); } // Returns true iff number is prime public static boolean isPrime(int number) { // determines if number is prime