SCJP 5, 1/7 Declarations, Initialization and Scoping

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Lecture 5: Interfaces.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Lecture 5:Interfaces and Abstract Classes
OOP: Encapsulation &Abstraction
Software Construction
Final and Abstract Classes
Inheritance and Polymorphism
Nested class.
Object Based Programming
Chapter 9 Inheritance and Polymorphism
Lecture 4: Interface Design
Object-Oriented Programming: Polymorphism
Interface.
Enumerations & Annotations
Enumerations & Annotations
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
(and a review of switch statements)
(and a review of switch statements)
Packages and Interfaces
Implementing Non-Static Features
Interfaces.
More On Enumeration Types
Java Inheritance.
Enumerations & Annotations
CIS 199 Final Review.
Chapter 8 Class Inheritance and Interfaces
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
Creating and Using Classes
Chengyu Sun California State University, Los Angeles
Presentation transcript:

SCJP 5, 1/7 Declarations, Initialization and Scoping Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports).

Agenda 1/3 Declaration Class declaration Class modifiers Abstract classes Inner Classes and Enclosing Instances

Agenda 2/3 Typesafe enumerations Properties of the enum type Enum constructors Methods provided for the enum types Extending enum types: constant-specific class bodies java.util.EnumSet java.util.EnumMap

Agenda 3/3 Creating and using packages Static imports Variable Identifiers

Declaration Class declarations define new reference types and describe how they are implemented Nested class: declaration occurs within the body of another class or interface Top level class == !(nested class) Named class may be declared abstract must if it is incompletely implemented cannot be instantiated, but can be extended by subclasses Final: can't have subclasses Public: can be referred to from other packages

Each class except Object is an extension of (subclass of) a single existing class and may implement interfaces Body of a class declares: members (fields and methods and nested classes and interfaces) instance and static initializers constructors

Scope of a member: entire declaration of the class to which the member belongs Field, method, member class, member interface, and constructor declarations may include the access modifiers public, protected, or private The members of a class include both declared and inherited members

Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared class members and interface members can hide class or interface members declared in a superclass or superinterface. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.

Field declarations describe: class variables, which are incarnated once instance variables, which are freshly incarnated for each instance of the class Final: can be assigned to only once Any field declaration may include an initializer Member class declarations describe nested classes that are members of the surrounding class. Member classes may be static, in which case they have no access to the instance variables of the surrounding class; or they may be inner classes. Member interface declarations describe nested interfaces that are members of the surrounding class.

ENUMS

Typesafe enumerations The J2SE 5.0 enum declaration looks as follows: public enum MainMenu {FILE, EDIT, FORMAT, VIEW}; enum MachineState { BUSY, IDLE, BLOCKED } // Canonical form enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }

Advantages of enums It provides strong compile-time type safety It provides a separate namespace for each enum type and thus eliminates the need to include a prefix in each constant name Constants are not compiled into clients so you can freely add, remove, or reorder them without recompiling the clients Printed values are informative instead of just numbers Enum constants can be used wherever objects can be used

public enum MainMenu {FILE, EDIT, FORMAT, VIEW}; Keyword enum is used (reserved word) This enum declaration generates a class (MainMenu), which automatically implements the Comparable and Serializable interfaces, and provides several members including: Static variables FILE, EDIT, FORMAT, and VIEW. Static method values(), which is an array containing the constants in the enum. Static method valueOf(String) that returns the appropriate enum for the string passed in. Appropriately overloaded equals(), hasCode(), toString(), and compareTo() methods.

enum An enum declaration is a special kind of class declaration: It can be declared at the top-level and as static enum declaration (w klasie, ale nie w metodzie) It is implicitly static, i.e. no outer object is associated with an enum constant. It is implicitly final unless it contains constant- specific class bodies, but it can implement interfaces. It cannot be declared abstract unless each abstract method is overridden in the constant- specific class body of every enum constant.

Enum constructors

Enum constructors Each constant declaration can be followed by an argument list that is passed to the constructor of the enum type having the matching parameter signature. An implicit standard constructor is created if no constructors are provided for the enum type. As an enum cannot be instantiated using the new operator, the constructors cannot be called explicitly.

Enum methods public enum Meal { BREAKFAST { public double mealPrice() { double breakfastPrice = 10.50; return breakfastPrice; } }; abstract double mealPrice(); // bez tego nie będzie dostępu

java.util.EnumSet enum Day {.MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY } EnumSet< Day > allDays = ...............EnumSet.range(Day.MONDAY, Day.SUNDAY); ...............out.println("All days: " + allDays); EnumSet< Day > weekend = ...............EnumSet.range(Day.SATURDAY, Day.SUNDAY); ...............out.println("Weekend: " + weekend); EnumSet< Day > weekDays = ...............EnumSet.complementOf(weekend); ...............out.println("Week days: " + weekDays);

java.util.EnumSet Enums can be used in a special purpose Set implementation (EnumSet) which provides better performance. Elements MUST come from a single enum. Represented internally as bit vectors. Defines new methods, implements Set/Collection interfaces. NOTE, all methods are static except for the clone() method. All methods return an EnumSet< E >. The null reference CANNOT be stored in an enum set.

java.util.EnumSet allOf(Class< E > elementType) clone() complementOf(EnumSet< E > s) copyOf(Collection< E > c) copyOf(EnumSet< E > s) noneOf(Class< E > elementType) of(E e), ..., of(E e1, E e2, E e3, E e4, E e5) range(E from, E to)

java.util.EnumMap int[] freqArray = { 12, 34, 56, 23, 5, 13, 78 }; // Create a Map of frequencies Map<Day, Integer> ordinaryMap = new HashMap<Day, Integer>(); for (Day day : Day.values()) { ordinaryMap.put(day, freqArray[day.ordinal()]); } // Create an EnumMap of frequencies EnumMap<Day, Integer> frequencyEnumMap = new EnumMap<Day, Integer>(ordinaryMap); // Change some frequencies frequencyEnumMap.put(Day.MONDAY, 100); frequencyEnumMap.put(Day.FRIDAY, 123); // Values Collection<Integer> frequencies = frequencyEnumMap.values(); // Keys Set<Day> days = frequencyEnumMap.keySet();

java.util.EnumMap // Creates an empty enum map with the // specified key type. EnumMap(Class< K > keyType) // Creates an enum map with the same key // type as the specified enum map, initially // containing the same mappings (if any). EnumMap(EnumMap< K,? extends V > m) // Creates an enum map initialized from the // specified map. EnumMap(Map< K,? extends V > m)

Creating and using packages Why? classes easier to find and to use avoid naming conflicts control access

Creating packages Package is a collection of related classes and interfaces providing access protection and namespace management. To create a package, you put a class or an interface in it: a package statement at the top of the source file

Creating packages Scope of the package statement: entire source file. If you put multiple classes in a single source file, only one may be public, and it must share the name of the source file. Only public package members are accessible from outside the package. No package statement: class or interface ends up in the default package (package that has no name).

Using packages One or more: Refer to the member by its long (qualified) name. graphics.Rectangle myRect = new graphics.Rectangle(); Import the package member import graphics.Circle; Import the members entire package import graphics.*; import graphics.A*; // does not work

Static imports package com.name; interface XYZ { ...public static final double Constant1 = someValue; ...public static final double Constant2 = anotherValue; } public class MyClass implements XYZ { .....double value = 2 * Constant1; ------------------------------ import static com.name.XYZ.*;

import static java.lang.Math.*; import static java.lang.System.*; With these two static imports, you now can use: double r = cos(PI * theta); instead of: double r = Math.cos(PI * theta); and out.println("Hello there"); System.out.println("Hello there");