Java Programming Chapter 3 More about classes. Why?  To make classes easier to find and to use  to avoid naming conflicts  to control access  programmers.

Slides:



Advertisements
Similar presentations
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Advertisements

CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
1 Classes Object-oriented programming: Model the problem as a collection of objects that have certain attributes and interact with one another and/or the.
Road Map Introduction to object oriented programming. Classes
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
EEC-681/781 Distributed Computing Systems Java Tutorial Wenbing Zhao Cleveland State University
1 Lecture 2 Java Packages  What are Java packages?  Why do wee need packages?  How to create a Java package?  Some examples.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
Unit 051 Packages What is a Package? Why use Packages? Creating a Package Naming a Package Using Package Members Managing Source and Class Files Visibility.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
CMP-MX21: Lecture 6 Objects & Methods 1 Steve Hordley.
Writing Classes (Chapter 4)
Packages F Package is a container for classes F A package is a grouping of related types (classes and interfaces) providing access protection and name.
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.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Object-Oriented Programming in C++
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
By Waqas The topmost class in the java class hierarchy is called “Object”. If you declare a class which does not sub class of any super class.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Packages. Creating and Using Packages To make types easier to find and use, to avoid naming conflicts, and to control access, programmers bundle groups.
Chapter 5 Introduction to Defining Classes
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
Classes, Interfaces and Packages
Packages. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L13: Layout Managers Slide 2.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
YG - CS Concept of Encapsulation What is encapsulation? - data and functions/methods are packaged together in the class normally.
Topics Instance variables, set and get methods Encapsulation
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
CS 100Lecture71 CS100J Lecture 7 n Previous Lecture –Computation and computational power –Abstraction –Classes, Objects, and Methods –References and aliases.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
© 2004 Pearson Addison-Wesley. All rights reserved September 5, 2007 Packages & Random and Math Classes ComS 207: Programming I (in Java) Iowa State University,
Java Packages  What are Java packages?  Why do we need packages?  How to create a Java package?  Some examples.  Coming Next: Program Documentation.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
SCJP 5, 1/7 Declarations, Initialization and Scoping
Software Construction
Classes Object-oriented programming: Example: Bank transactions
Introduction to Classes
Packages, Interfaces & Exception Handling
Packages Written part of final exam Alex Rudniy
More on Classes Classes may have constructors which are called when objects are created and destructors which are called when objects are destroyed. Classes.
Corresponds with Chapter 7
Package & Java Access Specifiers
CS100J Lecture 7 Previous Lecture This Lecture Java Constructs
Applying OO Concepts Using Java
Packages & Random and Math Classes
Introduction to Object-Oriented Programming
Final and Abstract Classes
Chapter 6 Objects and Classes
Presentation transcript:

Java Programming Chapter 3 More about classes

Why?  To make classes easier to find and to use  to avoid naming conflicts  to control access  programmers bundle groups of related classes and interfaces into packages.

Official Definition  A package is a collection of related classes and interfaces providing access protection and namespace management

Where?  The classes and interfaces that are part of the Java platform are members of various packages that bundle classes by function:  fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on.  You can put your classes and interfaces in packages, too.

Example  Suppose that you write a group of classes that represent a collection of graphic objects, such as circles, rectangles, lines, and points.  You also write an interface, Draggable, that classes implement if they can be dragged with the mouse by the user:

//in the Graphic.java file public class Graphic {... } //in the Circle.java file public class Circle extends Graphic implements Draggable {... } //in the Rectangle.java file public class Rectangle extends Graphic implements Draggable {... } //in the Draggable.java file public interface Draggable {... }

Why Bundle in a Package  You and other programmers can easily determine that these classes and interfaces are related.  You and other programmers know where to find classes and interfaces that provide graphics-related functions.  The names of your classes won’t conflict with class names in other packages, because the package creates a new namespace.  You can allow classes within the package to have unrestricted access to one another yet still restrict access for classes outside the package.

Creating a Package  you put a class or an interface in it.  To do this, you put a package statement at the top of the source file in which the class or the interface is defined.  For example, the following code appears in the source file Circle.java and puts the Circle class in the graphics package:

package graphics; public class Circle extends Graphic implements Draggable {... } The Circle class is a public member of the graphics package. You must include a package statement at the top of every source file that defines a class or an interface that is to be a member of the graphics package.

 So you would also include the statement in Rectangle.java and so on:  package graphics;  public class Rectangle extends Graphic implements Draggable  {... }  The scope of the package statement is the entire source file, so all classes and interfaces defined in Circle.java and Rectangle.java are also members of the graphics package.  If you put multiple classes in a single source file, only one may be public, and it must share the name of the source files base name.  Only public package members are accessible from outside the package.

 If you do not use a package statement, your class or interface ends up in the default package, which is a package that has no name.  the default package is only for small or temporary applications or when you are just beginning development.  Otherwise, classes and interfaces belong in named packages.

Naming a Package  With programmers all over the world writing classes and interfaces using the Java programming language, it is likely that two programmers will use the same name for two different classes.  The previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package.  Yet the compiler allows both classes to have the same name. Why?  Because they are in different packages, and the fully qualified name of each class includes the package name.  That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.

Using Package Members  Only public package members are accessible outside the package in which they are defined.  To use a public package member from outside its package, you must do one or more of the following: –Refer to the member by its long (qualified) name –Import the package member –Import the member's entire package –Each is appropriate for different situations, as explained in the following sections.

Refer to a Package my name  so far we’ve used simple names – for classes – Rectangle  you can use the simple name if its within the same package as that member – or if you have imported that package  But – if you want to use a package that has not been imported  graphics.Rectangle -- qualified name  You could use it to : graphics.Rectangle myRect = new graphics.Rectangle()

Importing a package member import graphics.Circle; Now you can refer to the Circle class by its simple name: Circle myCircle = new Circle();

Importing an entire package  To import all the classes and interfaces contained in a particular package, use the import statement with the asterisk (*) wildcard character:  import graphics.*;  Now you can refer to any class or interface in the graphics package by its short name: Circle myCircle = new Circle(); Rectangle myRectangle = new Rectangle();

JRS  For your convenience, the Java runtime system automatically imports three entire packages: –The default package (the package with no name) –The java.lang package –The current package by default

Class Variables  class variables are attributes common to all objects belonging to a certain class  These are also called static variables  static does not mean unchangeable  class variables declared static  exp – a variable that keeps a check on how many instances of a particular class there are at one time

Bank Account  every bank account – a particular balance  a particular account holder  these data need to be available in one instance for each account – ordinary instance variables  Interest rate – class variable  Since all accounts will have the same interest rate – inefficient to store this in every single account

public class Account { //class variables private static double interestRate; //class methods public static double getInterest ( ){ interestRate = newInterest; } //instance variables private int customerNo; private double balance, interestEarned;

//constructor public Account (int customer){ customerNo = customer; } //instance methods public double getBalance() { return balance; } public void transaction(double amount){ //negative amount => withdrawal if (amount < 0 && balance + amount < 0) System.out.println (“Withdrawal cannot be done”); System.out.println (“Withdrawal cannot be done”);else balance = balance + amount; }

public void getDailyInterest(){ interestEarned = interestEarned + balance * interestRate/100/365; } public void addInterest(){ balance = balance+interestEarned; interestEarned = 0; }}

 Every account has three class variables –keep track of customer numbers –current balance –interest earned during the year  constructor initializes a new account, a unique customer number is provided as an argument to the constructor  instance variables balance and interestEarned default to 0  getBalance is called – checks balance of account  transaction – called each time a deposit or withdrawal is made  getDailyInterest – called once a day – it calculates the interest earned  addInterest – called end of every year

class variable – interestRate use static class methods getInterest – setInterest – read and change the interest rate class variables and class methods can have modifiers – public, private … instance methods can have access to the class variables and methods – read and change if class variable is changed in an instance method, the change will affect all the objects since they all share same class

a class variable is initialized when the class is used for the first time in a program can initialize to a specific value will default to zero of not Constructors are not used to initialize class variables constructors only initialize the variables dealing with a particular instance of the class class variables are used to define constants – final

Recap: class variables are declared – static exist only in one edition – common to all objects belonging to the class are initialized when class is loaded exist for the remainder of the program can be initialized if necessary in a special class initializer are often used to define constants

Class Methods  methods marked with static  getInterest and setInterest  they do not handle individual accounts  they use only class variables no instance variables  if you try – compile will fail

Call Statements  Account.setInterest(4.5);  double ir = Account.getInterest();  also same as instance methods  Account acc = new Account(1234);  acc.setInterest(5.1); but setInterest does not read or change object acc – it changes something that affects all the objects of the class

And Finally  Not unusual to have a class with all class methods  used to encapsulate the methods  See class Math – pg 3.5