2015 Spring Content Class method [review] Access control

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

Final and Abstract Classes
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Road Map Introduction to object oriented programming. Classes
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
ECE122 Feb Introduction to Class and Object Java is an object-oriented language. Java’s view of the world is a collection of objects and their.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Lecture 9 Concepts of Programming Languages
Abstract Data Types and Encapsulation Concepts
Department of Computer Science
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
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.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Session 7 Methods Strings Constructors this Inheritance.
Classes One class usually represents one type of object –May contain its own member variables –May contain its own methods to operate on the member variables.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
L EC. 06: C LASS D ETAILS S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length.
Sahar Mosleh California State University San MarcosPage 1 Classes and Objects and Methods.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Topics Instance variables, set and get methods Encapsulation
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.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
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.
J AVA P ROGRAMMING 2 CH 04: C LASSES, O BJECTS AND M ETHODS (II) 0.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Topic: Classes and Objects
OOP: Encapsulation &Abstraction
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
3 Introduction to Classes and Objects.
Static data members Constructors and Destructors
Abstract Data Types and Encapsulation Concepts
Final and Abstract Classes
Inheritance and Polymorphism
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3: Using Methods, Classes, and Objects
Lecture 4-7 Classes and Objects
Lecture 9 Concepts of Programming Languages
Object Based Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Corresponds with Chapter 7
Abstract Data Types and Encapsulation Concepts
Object-Oriented Programming
Classes & Objects: Examples
Group Status Project Status.
Learning Objectives Classes Constructors Principles of OOP
Constructors and Other Tools
Classes and Objects.
Classes One class usually represents one type of object
Java Programming Language
Final and Abstract Classes
ITE “A” GROUP 2 ENCAPSULATION.
Chapter 7 Objects and Classes
CSG2H3 Object Oriented Programming
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Lec. 06: Class Details

2015 Spring Content Class method [review] Access control Passing arguments Method overloading Variable-length Arguments [不測驗,可列補充教材] Recursion Using the keyword static Nested classes Shadowing

classes and objects In Java, a class is a template/blueprint that defines both the data and the code that will operate on that data. Each class definition is a data type. Java uses a class specification to construct objects. Objects are instances of a class by specifying object states. The methods and fields that constitute a class are called members of the class. Data members are referred to as instance variables

Example 1 of creating and referencing an object /* A program that uses the Vehicle class. Call this file VehicleDemo.java */ class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg; // fuel consumption in miles per gallon } Template members

public static void main(String args[]) { class VehicleDemo { public static void main(String args[]) { Vehicle minivan = new Vehicle(); int range; // assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; // compute the range assuming a full tank of gas range = minivan.fuelcap * minivan.mpg; System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range); } 設計圖 reference instance

Example 2 of creating and referencing an object minivan passengers class Vehicle { int passengers; int fuelcap; int mpg; } class TwoVehicles { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); int range1, range2; // assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; 7 feulcap 16 mpg 21 sportscar passengers 2 feulcap 14 mpg 12

// assign values to fields in sportscar sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; // compute the ranges assuming a full tank of gas range1 = minivan.fuelcap * minivan.mpg; range2 = sportscar.fuelcap * sportscar.mpg; System.out.println("Minivan can carry " + minivan.passengers + " with a range of " + range1); System.out.println("Sportscar can carry " + sportscar.passengers + " with a range of " + range2); }

Method: Parameters and arguments A parameter is a special kind of variable, used in a method to refer to one of the pieces of data provided as input to the method. An argument is a value sent from the caller to the invoked method. The mapping between parameters and arguments is based on their positions. The value of the first argument is copied into the first parameter, the value of the second argument into the second parameter, and so on. A parameter is within the scope of its method, and aside from its special task of receiving an argument, it acts like any other local variables.

Adding a parameterized method to vehicle class Vehicle { int passengers; int fuelcap; int mpg; int range() { return mpg * fuelcap; } double fuelneeded(int miles) { return (double) miles / mpg; parameter

class CompFuel { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(); double gallons; int dist = 252; minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; sportscar.passengers = 2; sportscar.fuelcap = 14; sportscar.mpg = 12; gallons = minivan.fuelneeded(dist); System.out.println("To go " + dist + " miles minivan needs " + gallons + " gallons of fuel."); gallons = sportscar.fuelneeded(dist); System.out.println("To go " + dist + " miles sportscar needs " + gallons + " gallons of fuel."); } argument

Constructors A constructor of a class is syntactically similar to a method, but with no explicit return type, which initializes an object or performs any other startup procedures required to create a fully formed object when it is created. Each class has at least one constructor. If there is no constructor specified in a class, javac automatically adds a default constructor. A default constructor is a non-arg, i.e. without parameter, constructor and does nothing If there is a constructor defined, no default constructor will be added by javac. The name of a constructor must be the same as the class name. A class may have more than one constructor, but with different parameter list. Constructors are only activated by the new operator.

Example of using constructors // A simple constructor. class MyClass { int x; MyClass() { x = 10; } class ConsDemo { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(); System.out.println(t1.x + " " + t2.x); 10 10

Example of using constructors class MyClass { int x, y; MyClass() { x = 0; y = 0; } MyClass(int a) { x = a; y = 0; } MyClass(int a, int b) { x = a; y = b; } } class DemoMyClass { public static void main(String args[]) { MyClass t1 = new MyClass(); MyClass t2 = new MyClass(5); MyClass t3 = new MyClass(4, 3 + 4); System.out.println(t1.x + " " + t2.x + " " + t3.x); 0 5 4

Exercise 1 Method with Constructor Ex1a. 計算華氏溫度 class DegreeInC { int temperature; DegreeInC(int t) { … } double convert() { … } } Ex1b. 計算 [a, b]區間中整數的總和 class Region { int left_margin; int right_margin; Region(int l, int r) { … } int sum() { … }

Exercise 2 Complete the count method which returns the number of elements in array A that is less than the integer n. class Ex8{ public static void main(String args[]) { Scanner scn = new Scanner(System.in); int A[] = { 6, 7, 7, 3, 6, 7, 4 }; int n = scn.nextInt(); Problem p = new Problem (); System.out.println(p.count(n, A)); } class Problem { (待完成)

Encapsulation and information hiding Java provides class construct to support encapsulation and information hiding. Using class construct, programmers can use the data and services provided by another class to complete tasks without knowing the implementation details of the class. Remember that you have use System, PrintStream, Integer and Scanner classes in J2SDK without knowing their implementation details.

More requirement for encapsulation and information hiding Thinking about the following scenario. You are about to design a class Clock to represent clocks which provide the functions of setting and displaying date and time, and also setting the alarm. How to prevent a user from setting a illegal date and/or time, such as Feb. 30, 2013? To complete your design, you need a mechanism to protect the fields from directly accessing by users and only allow users to access the fields through the methods in the same class. The values set to fields can be verified by the methods. Java provides access modifiers to protect the members of a class.

Access modifiers Java provides 3 access modifiers for declaring class members : public, protected and private. Java provides 4 access modes. Visible to everyone: using public Visible to the package and subclasses: using protected Visible to the package, but not subclasses: declared without any access modifier Visible to the class only: using private When a member is declared with a access modifier, the access modifier must be the first keyword. The ordering, based on the strength of restriction, of the 4 types of access modes from least to most is public, protected, default and private. When you select a proper access modifier for a field, follow the principle of least privilege. Since the scope of local variables and parameters is within the method which defines the variables, they cannot be declared with any access modifier.

Modifier Same Class Same Package Subclass Universe private Yes default protected public

Packages In Java, a package means a group of functional related classes. Packages are both an organizational and an access control feature. The access control feature will be discussed in later lecture. A package is similar to a directory in Microsoft Windows. A package may contain packages and classes. A package and its sub-packages/classes are separated by dot. A fully-qualified class name consists of all the package names starting from the root, e.g. the fully qualified class name for System is java.lang.System.

Example of using public and private class data { private int i=10; public int j=20; void display() { System.out.println("a.i=" + i); } class App172 public static void main(String[] args) data a = new data(); // system.out.println("a.i=" + a.i); a.display(); System.out.println("a.j=" + a.j); app172.java:18: error: i has private access in data System.out.println("a.i=" + a.i); ^ 1 error a.i=10 a.j=20

Example ♥ class AccessDemo { class MyClass { private int alpha; public int beta; int gamma; // default access void setAlpha(int a) { alpha = a; } int getAlpha() { return alpha; class AccessDemo { public static void main(String args[]) { MyClass ob = new MyClass(); ob.setAlpha(-99); System.out.println("ob.alpha is " + ob.getAlpha()); // ob.alpha = 10; // Wrong! alpha is private! ob.beta = 88; ob.gamma = 99; } ♥ ob.alpha is -99

Example Modifier Same Class Same Package Subclass Universe private Yes default protected public class MyClass { public int alpha = 1; protected int beta =2; int gamma =3; private int lambda = 4; void setLambda(int a) { lambda = a * alpha + beta / gamma; } int getLambda() { return lambda; class AccessDemo2 { public static void main(String args[]) { MyClass ob = new MyClass(); ob.setLambda(-99); System.out.println("ob Lambda is " + ob.getLambda()); ob.alpha = 77;; ob.beta = 88; ob.gamma = 99; ob Lambda is -99

Getters and setters By convention, fields should be declared as private and accessed through methods. The method used to set the value of a field is called setter. The name of a setter, by convention and JavaBeans specification, is beginning with “set” and then the field name (capitalized the first character of the field name). Example: setLambda() The method used to get the value of a field is called getter. The name of a getter, by convention and JavaBeans specification, is beginning with “get” and then the field name (capitalized the first character of the field name). Example: getLambda()

Exercise 3 Create a class called Test. 利用Test來維護一個陣列. class Test { private int data[]; Test() … } public void setData(int index, int value) public int getData(int index) API example public void setData(int index, int value) public int getData(int index) http://docs.oracle.com/javase/7/docs/api/ 2 hr