Use interfaces to define constants?

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Multiple Choice Solutions True/False a c b e d   T F.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
CS-434: Object-Oriented Programming Using Java Week 2
Inheritance. Introduction Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications.
AP Computer Science A – Healdsburg High School 1 Interfaces, Abstract Classes and the DanceStudio - Similarities and Differences between Abstact Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Inheritance Inheritance is the process of extending the functionality of a class by defining a new class that inherit,all the features of extending class.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Variations on Inheritance Object-Oriented Programming Spring
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Java Interfaces CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (see Chapter 9 of.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
SCJP 5, 1/7 Declarations, Initialization and Scoping
Modern Programming Tools And Techniques-I
Copyright © Jim Fawcett Spring 2017
Java Generics.
Topic: Classes and Objects
Chapter 15 Abstract Classes and Interfaces
OOP: Encapsulation &Abstraction
CSC 243 – Java Programming, Spring 2014
Software Construction
Software Development Java Classes and Methods
Inheritance and Polymorphism
Object Oriented Programming using Java - Class Instance Variables
Chapter 5 Hierarchies IS-A associations superclasses subclasses
Structs.
Classes A class is a blueprint of an object
UML Class Diagram: class Rectangle
Class vs Abstract vs Interface
Functional Programming with Java
Lecture 14 - Abstract Classes
CS240: Advanced Programming Concepts
Object Based Programming
Object-Oriented Programming: Polymorphism
Abstract Classes AKEEL AHMED.
Interfaces.
More On Enumeration Types
Lecture 14- Abstract Classes
Advanced Java Programming
METHOD OVERRIDING in JAVA
Singleton design pattern
Java Inheritance.
Fundaments of Game Design
Chapter 14 Abstract Classes and Interfaces
CSC 220 – Processing Spring, 2017
Class.
5. 3 Coding with Denotations
CS 112 Programming 2 Lecture 02 Abstract Classes & Interfaces (2)
Object Oriented Programming
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
CS 240 – Advanced Programming Concepts
CSG2H3 Object Oriented Programming
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Use interfaces to define constants? public interface ScienceConstants { static final double PI = 3.14; static final double BOLTZMANN_CONSTANT = 1.3806503e-23; } Good Java Programming 6/19/2018

Alternative 1 Use Enums Enums in Java are full fledged classes (Java 1.5) More powerful than enums in C++ where they are just int values By nature, Enums are immutable All fields should be final Make the fields private and provide accessors/mutators Good Java Programming 6/19/2018

Do NOT use interfaces to define constants The use of constants in a class should be considered implementation detail If a non-final class implements an interface, all its subclasses will have their namespaces polluted by the constants in the interface Java uses constant interfaces in its libraries (example: java.io.ObjectStreamConstants) treat these as anomalies Good Java Programming 6/19/2018

Alternative 2 Use Constant Utility class public class PhsyicalConstants { private PhysicalConstants() { } //prevent instantiation static final double PI = 3.14; static final double BOLTZMANN_CONSTANT = 1.3806503e-23; } Usage: double circ = 2 * PhysicalConstants.PI * radius; Good Java Programming 6/19/2018

Alternative 2: continued Use Constant Utility class If it is heavily used, then you don’t need to qualify it each time use static import facility, introduced in java 1.5 public class MyTest { import static PhysicalConstants.*; double myMethod () { double circ = 2 * PI * radius; … } Good Java Programming 6/19/2018

More on Enums Java Enums are classes that export one instance for each enumeration constant via a public static final field Enum types are effectively final no accessible constructor clients can neither create instances or extend it so, enum types are instance controlled Enums are generalization of Singletons Singleton is a single element enum Good Java Programming 6/19/2018

More on Enums (2) Enums provide compile-time type safety Enums with identically named constants can co-exist as each type has its own namespace Can augment Enums with methods just like any Java class Good Java Programming 6/19/2018

More on Enums (3) Has a static values(…) method that returns an array of its values in the order it was declared example in next slides Default toString() returns the declared name of each enum value can be overridden Good Java Programming 6/19/2018

Enum Example public enum CourseAnalysis { cs240 (4, 81.5, 55), cs654 (3, 79.8, 41); // semi colon here private final int numCredits; private final double avgScore; private final int numStudents; private static final double NO_OF_EXAMS = 3; // Constructor CourseAnalysis(int numCreditsIn, double avgScoreIn, int numStudentsIn) { numCredits = numCreditsIn; avgScore = avgScoreIn; numStudents = numStudentsIn; } Good Java Programming 6/19/2018

Enum Example (continued) public int getNumCredits() { return numCredits; } public double getAvgScore() { return avgScore; } public int getNumStudents() { return numStudents; } // dummy method, just an example // note: calculation is not intended to make sense … public double someWeightedAverage(double weight) { return weight * numCredits * avgScore / numStudents; } Good Java Programming 6/19/2018

Enum: can’t instantiate like a Java object // Try calling the constructor CourseAnalysis cA = new CourseAnalysis(3, 3.14, 7); Driver.java:91: enum types may not be instantiated [javac] CourseAnalysis cA = new CourseAnalysis(3, 3.14, 7); [javac] ^ [javac] 1 error BUILD FAILED Good Java Programming 6/19/2018

Enum: cannot directly access private data members // try to access the private data member directly System.out.printf("Enum member: average score is %f ", CourseAnalysis.cs342.avgScore); Error: avgScore has private access in test.util.CourseAnalysis Good Java Programming 6/19/2018

Enum: default toString() System.out.printf("Enum member is %s %n", CourseAnalysis.cs342); Output: [java] Enum member is cs342 Good Java Programming 6/19/2018

Enum: accessing methods // access methods like a standard Java object System.out.printf("Enum member: average score is %f %n", CourseAnalysis.cs342.getAvgScore()); Output: [java] Enum member: average score is 84.300000 Good Java Programming 6/19/2018

Enum: foreach double weightValue = 0.77; for (CourseAnalysis c : CourseAnalysis.values()) { System.out.printf("WeightedAvg of %s is %f %n", c, c.someWeightedAverage(weightValue)); } [java] WeightedAvg of cs240 is 4.564000 [java] WeightedAvg of cs342 is 7.418400 [java] WeightedAvg of cs654 is 4.496049 Good Java Programming 6/19/2018

Design Guideline The constant interface pattern is a poor use of interfaces Good Java Programming 6/19/2018