Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc.

Slides:



Advertisements
Similar presentations
Basic -2 Classes and Objects. Classes and Objects A class is a complex data TYPE An object is an instance of a class. Example: Class: Person Objects:
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Class Hierarchies. Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Access to Names Namespaces, Scopes, Access privileges.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Sub and superclasses using extends
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
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.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Review Java.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
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.
Classes CS 21a: Introduction to Computing I First Semester,
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
CSE 1301 Lecture 5 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Chapter 7 Object-Oriented Programming Part 2: User-Defined Classes.
Introduction to Java Java Translation Program Structure
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
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.
CSE 1301 Lecture 6 Writing Classes Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces and Inner Classes
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.
Java – Methods Lecture Notes 5. Methods All objects, including software objects, have state and behavior. example, a student as an object has name, address,
Java Programming, Second Edition Chapter Three Using Methods, Classes, and Objects.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP Basics Classes & Methods (c) IDMS/SQL News
Object-Oriented Programming: Classes and Objects Chapter 1 1.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Object-Oriented Programming: Classes and Objects
OBJECT ORIENTED PROGRAMMING II LECTURE 7 GEORGE KOUTSOGIANNAKIS
CompSci 230 S Programming Techniques
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Lecture 14 Writing Classes part 2 Richard Gesick.
Lecture 13 Writing Classes Richard Gesick.
Chapter 9 Inheritance and Polymorphism
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Implementing Non-Static Features
Tonga Institute of Higher Education
CS 240 – Advanced Programming Concepts
Presentation transcript:

Class Modifiers So far we have seen many examples of such modifiers E.g. Public Abstract etc

Terminology Access Modifier –determines access rights for the class and its members –defines where the class and its members can be used

Class Modifiers A class declaration may include class modifiers. ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final strictfp

Field Modifiers FieldModifiers: FieldModifier FieldModifiers FieldModifier FieldModifier: one of public protected private static final transient volatile

Why use these It is important in many applications to hide data from the programmer E.g., a password program must be able to read in a password and compare it to the current one or allow it to be changed But the password should never be accessed directly! public class Password { public String my_password; : } Password ProtectMe; : ProtectMe.my_password = “backdoor”; // this is bad

Public etc public means that any class can access the data/methods private means that only the class can access the data/methods protected means that only the class and its subclasses can access the data/methods

Access Modifiers Access ModifierClass or member can be referenced by… publicmethods of the same class, and methods of other classes privatemethods of the same class only protectedmethods of the same class, methods of subclasses, and methods of classes in the same package No access modifier (package access) methods in the same package only

public vs. private Classes are usually declared to be public Instance variables are usually declared to be private Methods that will be called by the client of the class are usually declared to be public Methods that will be called only by other methods of the class are usually declared to be private

public Public access Most liberal kind of access Class or field is accessible everywhere When a method or variable is labelled with the keyword public it means that any other class or object can use that public method or variable When a class is labelled with the keyword public, it means the class can be used by any other class The keyword private is used to restrict access and prevent inheritance!

Private Private if its only visible from inside the class definition This is compromised somewhat by public access methods

Example public class Secret { private String theSecret; private String getSecret (){... } Both theSecret and getSecret variables are only accessible inside the class

Consider public class NotSoSecret extends Secret {... public void getSecret(){ super.getSecret();... } You can’t access getSecret by inheritance because its private

Secret mySecret; NotSoSecret myDiary;... mySecret.getSecret(); myDiary.getSecret(); Cannot invoke the getSecret method on mySecret since it’s private. Can invoke getSecret on myDiary because it’s public in class NotSoSecret

Class Modifiers A class declaration may include class modifiers. ClassModifiers: ClassModifier ClassModifiers ClassModifier ClassModifier: one of public protected private abstract static final strictfp

strictfp Classes The effect of the strictfp modifier is to make all float or double expressions within the class declaration be explicitly FP-strict This implies that all methods declared in the class, and all nested types declared in the class, are implicitly strictfp. Don’t worry about this for now

Defining Instance Variables Syntax: accessModifier dataType identifierList; dataType can be primitive date type or a class type identifierList can contain: –one or more variable names of the same data type –multiple variable names separated by commas –initial values Optionally, instance variables can be declared as final

Examples of Instance Variable Definitions private String name = ""; private final int PERFECT_SCORE = 100, PASSING_SCORE = 60; private int startX, startY, width, height;

Tips Define instance variables for the data that all objects will have in common. Define instance variables as private so that only the methods of the class will be able to set or change their values. Begin the identifier name with a lowercase letter and capitalize internal words.

The Auto Class public class Auto { private String model; private int milesDriven; private double gallonsOfGas; }

Field Modifiers FieldModifiers: FieldModifier FieldModifiers FieldModifier FieldModifier: one of public protected private static final transient volatile

static If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created. A static field, sometimes called a class variable, is incarnated when the class is initialized

static Variables Also called class variables One copy of a static variable is created per class static variables are not associated with an object static constants are often declared as public To define a static variable, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName; Example: public static int countAutos = 0;

static Methods Also called class methods Often defined to access and change static variables static methods cannot access instance variables: – static methods are associated with the class, not with any object. –static methods can be called before any object is instantiated, so it is possible that there will be no instance variables to access.

Rules for static and Non-static Methods See Examples 7.12 and 7.13 static Method Non-static Method Access instance variables?noyes Access static class variables?yes Call static class methods?yes Call non-static instance methods? noyes Use the object reference this?noyes

final Fields A field can be declared final Both class and instance variables (static and non-static fields) may be declared final. Effectively final declares the variable to be constant

Example private final int PERFECT_SCORE = 100,

To stop a class being inherited from (sub-classes) we can declare it as a final class e.g. If Person was declared as final final class Person {... // the body of the class... }

Then the following would not be allowed: class Programmer extends Person {... // the body of the class... }

Transient and volatile We will go back to these

Method Return Types The return type of a method is the data type of the value that the method returns to the caller. The return type can be any of Java's primitive data types, any class type, or void. Methods with a return type of void do not return a value to the caller.

Method Body The code that performs the method's function is written between the beginning and ending curly braces. Unlike if statements and loops, these curly braces are required, regardless of the number of statements in the method body. In the method body, a method can declare variables, call other methods, and use any of the program structures we've discussed, such as if/else statements, while loops, for loops, switch statements, and do/while loops.

main is a Method public static void main( String [] args ) { // application code } Let's look at main's API in detail: public main can be called from outside the class. (The JVM calls main.) static main can be called by the JVM without instantiating an object. void main does not return a value String [] args main's parameter is a String array

Value-Returning Methods Use a return statement to return the value Syntax: return expression;

Class Scope Instance variables have class scope –Any constructor or method of a class can directly refer to instance variables. Methods also have class scope –Any method or constructor of a class can call any other method of a class (without using an object reference).

Local Scope A method's parameters have local scope, meaning that: –a method can directly access its parameters. –a method's parameters cannot be accessed by other methods. A method can define local variables which also have local scope, meaning that: –a method can access its local variables. –a method's local variables cannot be accessed by other methods.

Summary of Scope A method in a class can access: –the instance variables of its class –any parameters sent to the method –any variable the method declares from the point of declaration until the end of the method or until the end of the block in which the variable is declared, whichever comes first –any methods in the class

Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } (returnType is the same data type as the instance variable)

Accessor Methods Example: the accessor method for model. public String getModel( ) { return model; }

Mutator Methods Allow client to change the values of instance variables public void setInstanceVariable( dataType newValue ) { // validate newValue, // then assign to instance variable }

Mutator Methods Example: the mutator method for milesDriven public void setMilesDriven( int newMilesDriven ) { if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven; else { System.err.println( "Miles driven " + "cannot be negative." ); System.err.println( "Value not changed." ); }

Data Manipulation Methods Perform the "business" of the class. Example: a method to calculate miles per gallon: public double calculateMilesPerGallon( ) { if ( gallonsOfGas != 0.0 ) return milesDriven / gallonsOfGas; else return 0.0; }

The Object Reference this How does a method know which object's data to use? this is an implicit parameter sent to methods and is an object reference to the object for which the method was called. When a method refers to an instance variable name, this is implied Thus: variableName model is understood to be is understood to be this.variableName this.model

Using this in a Mutator Method public void setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Example: public void setModel( String model ) { this.model = model; } this.model refers to the instance variable. model refers to the parameter.

The toString Method Returns a String representing the data of an object Client can call toString explicitly by coding the method call.

Example Client can call toString implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // explicit toString call System.out.println( compact.toString( ) ); // implicit toString call System.out.println( compact );

The toString API Return value Method name and argument list StringtoString( ) returns a String representing the data of an object

Auto Class toString Method public String toString( ) { DecimalFormat gallonsFormat = new DecimalFormat( "#0.0" ); return "Model: " + model + "; miles driven: " + milesDriven + "; gallons of gas: " + gallonsFormat.format( gallonsOfGas ); }

The equals Method Determines if the data in another object is equal to the data in this object Return valueMethod name and argument list booleanequals( Object obj ) returns true if the data in the Object obj is the same as in this object; false otherwise.

Example Example client code using Auto references auto1 and auto2: if ( auto1.equals( auto2 ) ) System.out.println( "auto1 equals auto2" );

Auto Class equals Method public boolean equals( Auto autoA ) { if ( model.equals( autoA.model ) && milesDriven == autoA.milesDriven && Math.abs( gallonsOfGas - autoA.gallonsOfGas ) < ) return true; else return false; }

Consider A bank account always has methods for depositing and querying the balance To maintain the privacy of a client’s balance and still allow methods in subclasses to change the balance we need to introduce a new access modifier called protected

protected If you create a protected data field or method it can be used within its own class or any subclass extended from it but not from the outside world

Example A standard bank account implements methods for depositing and querying the current balance: public class StandardAccount extends Account { protected double balance; Account (){ balance = 0.0; } public void lodgement (double amt){ balance = balance + amt; } public double getBalance (){ return balance; }

Exercises 1. True or false? Any of the access modifiers, public, protected, or private, can be applied to a top-level class. 2. Which, if any, of the following declarations are legal? A. public MyClass {//...} B. public protected int myVar; C. friendly Button myButton; D. Label myLabel

3. True or false? Access modifiers control which classes may use a feature. A class' features are: The class itself. Its class variables. Its methods and constructors

4. True or false? Top-level classes that are declared private may be accessed only by other classes in the same package.