L EC. 06: C LASS D ETAILS 0. 2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length.

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.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
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
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
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.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
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.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 4 Introduction to Classes, Objects, Methods and strings
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.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
L EC. 06: C LASS D ETAILS (2/2) 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.
L EC. 07: I NHERITANCE S PRING C ONTENT  Inheritance basics  Member access and inheritance  Constructors and inheritance  Superclass references.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
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.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
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.
2015 Spring Content Class method [review] Access control
Topic: Classes and Objects
Final and Abstract Classes
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3: Using Methods, 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
Object-Oriented Programming
Learning Objectives Classes Constructors Principles of OOP
Classes One class usually represents one type of object
Java Programming Language
Final and Abstract Classes
ITE “A” GROUP 2 ENCAPSULATION.
CSG2H3 Object Oriented Programming
Lecture 9 Concepts of Programming Languages
Presentation transcript:

L EC. 06: C LASS D ETAILS 0

2015 S PRING C ONTENT  Class method [review]  Access control  Passing arguments  Method overloading  Variable-length Arguments [ 不測驗,可列補充教材 ]  Recursion  Using the keyword static  Nested classes  Shadowing 1

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 2

1. /* A program that uses the Vehicle class. 2. Call this file VehicleDemo.java 3. */ 4. class Vehicle { 5. int passengers;// number of passengers 6. int fuelcap;// fuel capacity in gallons 7. int mpg;// fuel consumption in miles per gallon 8. } 3 members Template E XAMPLE 1 OF CREATING AND REFERENCING AN OBJECT

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

E XAMPLE 2 OF CREATING AND REFERENCING AN OBJECT 1. class Vehicle { 2. int passengers; 3. int fuelcap; 4. int mpg; 5. } class TwoVehicles { 8. public static void main(String args[]) { 9. Vehicle minivan = new Vehicle(); 10. Vehicle sportscar = new Vehicle(); int range1, range2; 13. // assign values to fields in minivan 14. minivan.passengers = 7; 15. minivan.fuelcap = 16; 16. minivan.mpg = 21; 5 minivan sportscar passengers 7 feulcap 16 mpg 21 passengers 2 feulcap 14 mpg 12

1. // assign values to fields in sportscar 2. sportscar.passengers = 2; 3. sportscar.fuelcap = 14; 4. sportscar.mpg = 12; // compute the ranges assuming a full tank of gas 7. range1 = minivan.fuelcap * minivan.mpg; 8. 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); 15. } 16. } 6

M ETHOD : P ARAMETERS 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. 7

A DDING A PARAMETERIZED METHOD TO VEHICLE 1. class Vehicle { 2. int passengers; 3. int fuelcap; 4. int mpg; int range() { 7. return mpg * fuelcap; 8. } double fuelneeded(int miles) { 12. return (double) miles / mpg; 13. } 14. } 8 parameter

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

C ONSTRUCTORS  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. 10

E XAMPLE 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); } 11 10

E XAMPLE 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); }

E XERCISE 1 M ETHOD WITH C ONSTRUCTOR 13  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() { … } }

E XERCISE 2 14  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 { ( 待完成 ) }

E NCAPSULATION 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. 15

M ORE 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. 16

A CCESS 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. 17

Spring Java Programming ModifierSame ClassSame PackageSubclassUniverse privateYes defaultYes protectedYes publicYes

P ACKAGES  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. 19

E XAMPLE 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); } 20 a.i=10 a.j=20 app172.java:18: error: i has private access in data System.out.println("a.i=" + a.i); ^ 1 error

E XAMPLE class MyClass { private int alpha; public int beta; int gamma; // default access void setAlpha(int a) { alpha = a; } int getAlpha() { return alpha; } 21 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 ♥

E XAMPLE 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; } 22 ob Lambda is -99 Modifier Same Class Same Package SubclassUniverse privateYes defaultYes protectedYes publicYes

G ETTERS 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() 23

E XERCISE 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) { … } 2 hr public void setData(int index, int value) public int getData(int index) API example 24