Java Enum Java, winter semester ,2018 1

Similar documents
JAVA V Assertions Java, winter semester

JAVA V Annotations Java, winter semester ,2016 1

INHERITANCE. Spring 2019

interface MyAnno interface str( ) val( )

Abstract Classes and Interfaces

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

C12a: The Object Superclass and Selected Methods

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Inheritance. The Java Platform Class Hierarchy

public static boolean isoutside(int min, int max, int value)

CMSC 132: Object-Oriented Programming II

Class, Variable, Constructor, Object, Method Questions

Methods Common to all Classes

New Features in Java 8

Java Fundamentals (II)

Advanced programming for Java platform. Introduction

Java Magistère BFA

Language Features. 1. The primitive types int, double, and boolean are part of the AP

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

Java: advanced object-oriented features

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

Rules and syntax for inheritance. The boring stuff

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance. Transitivity

Inheritance (Part 5) Odds and ends

public static void negate2(list<integer> t)

Index COPYRIGHTED MATERIAL

a guide to an object oriented programming language Niket Sheth JAVA

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

Declarations and Access Control SCJP tips

CLASS DESIGN. Objectives MODULE 4

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

Polymorphism. return a.doublevalue() + b.doublevalue();

Enum Types. Built-in support for types of discrete values Advantages over C++ s enum: Type-safety Body can include methods and fields

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

1 Shyam sir JAVA Notes

EMBEDDED SYSTEMS PROGRAMMING More About Languages

COP 3330 Final Exam Review

Interfaces. James Brucker

The class Object. Lecture CS1122 Summer 2008

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance and Polymorphism

LAMBDA EXPRESSIONS. Summer 2018

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

CS 251 Intermediate Programming Inheritance

Introduction to Inheritance

This page intentionally left blank

AP CS Unit 6: Inheritance Notes

Chapter 4 Defining Classes I

CS260 Intro to Java & Android 03.Java Language Basics

Java Lectures. Enhancements in Java 1.5

More about inheritance

Java Classes, Inheritance, and Interfaces

CMSC 132: Object-Oriented Programming II

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Programming overview

Super-Classes and sub-classes

CSE 331 Lecture 4. Comparing objects; cloning

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Documenting Java Code. Javadoc: The Tool and the Legend

Annotation File Specification

CH. 2 OBJECT-ORIENTED PROGRAMMING

Java Object Oriented Design. CSC207 Fall 2014

UCLA PIC 20A Java Programming

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Using Type Annotations to Improve Your Code

CS 251 Intermediate Programming More on classes

Array. Prepared By - Rifat Shahriyar

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Java Bytecode (binary file)

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Streams and Pipelines

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

LAMBDA EXPRESSIONS AND STREAMS API

COMP 250 Fall inheritance Nov. 17, 2017

More On inheritance. What you can do in subclass regarding methods:

Inheritance (continued) Inheritance

Programming II (CS300)

Java: introduction to object-oriented features

Fontys Hogeschool voor Techniek en Logistiek. March 13, 2018

Introduction to Object-Oriented Programming

Making New instances of Classes

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Lecture 2: Java & Javadoc

Annotations in Java. Jeszenszky, Péter University of Debrecen, Faculty of Informatics

Overriding methods. Changing what we have inherited from e.g. Object

Cloning Enums. Cloning and Enums BIU OOP

Java Overview An introduction to the Java Programming Language

Lambdas & Streams In JDK 8: Beyond The Basics

Produced by. Agile Software Development. Eamonn de Leastar

Building Java Programs. Inheritance and Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Transcription:

Java Enum 1

Enumerations <= Java 1.4 public static final int COLOR_BLUE = 0; public static final int COLOR_RED = 1; public static final int COLOR_GREEN = 2; possible problems type (un)safety no namespace constants hard-compiled in clients only numbers when printed 2

Enum public enum Color { BLUE, RED, GREEN... public Color clr = Color.BLUE; normal class can have fields, methods, even the main method subclass of java.lang.enum for each value single instance public static final field protected constructor 3

Enum without enum how to implement enum in Java 1.4 (and how enums are implemented) class Color { private int value; public static final Color RED = new Color(0); public static final Color GREEN = new Color(1); public static final Color BLUE = new Color(2); private Color(int v) { value = v;... 4

java.lang.enum public abstract class Enum <E extends Enum<E>> {... methods String name() int ordinal() each enum has the method values() returns an array with all enum's values public Colors clr = Colors.BLUE; System.out.println(clr); BLUE 5

Fields and methods public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6),... private final double mass; private final double radius; Planet(double mass, double radius){ this.mass = mass; this.radius = radius; double surfacegravity() { return G * mass / (radius * radius); 6

Fields and methods example public enum Operation { PLUS, MINUS, TIMES, DIVIDE; double eval(double x, double y){ switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; throw new AssertionError("Unknown op: " + this); 7

Fields and methods abstract methods particular implementations with each of the values public enum Operation { PLUS { double eval(double x, double y) { return x+y;, MINUS { double eval(double x, double y) { return x-y;, TIMES { double eval(double x, double y) { return x*y;, DIVIDE { double eval(double x, double y) { return x/y;; abstract double eval(double x, double y); 8

enum cannot be extended enum MoreColors extends Colors why? enum Color { Red, Green final class Color extends java.lang.enum<color> { public static final Color Red; public static final Color Green;... 9

Java Variable number of arguments 10

... three dots only as the last argument either an array or list of arguments can be passed in the method, available as an array void argtest(object... args) { for (int i=0;i <args.length; i++) { System.out.println(args[i]); argtest("hello", "how", "are", "you"); argtest(new Object[] {"Hello", "how", "are", "you"); methods printf System.out.printf("%s %d\n", user, total); 11

Test Are the calls equivalent? argtest("ahoj", "jak", "se", "vede"); argtest(new Object[] {"Ahoj", "jak", "se", "vede"); argtest((object) new Object[] {"Ahoj", "jak", "se", "vede"); a) Yes, all of them b) Only 1. and 2. c) Only 2. and 3. d) Each of them will print something different 12

JAVA Annotations 13

Annotations (metadata) since Java 5 allow attaching information to elements of code (to classes, methods, fields,...) in general, can be used in the same places as visibility modifiers but also elsewhere written as @NameOfAnnotation own annotations can be created can be specified, where can be used, how can be used,... predefined annotations in the package java.lang @Deprecated @Override @SuppressWarnings... 14

Annotations can have arguments @Deprecated(since="1.2", forremoval=true) arguments can have default values i.e., can be used without argument value @Deprecated where can be used classes, fields, methods method arguments, packages type usage can restricted in the annotation definition 15

Predefined annotations @Override marks a method that overrides the method from a parent in a case that nothing is overridden => the compiler will not compile the class usage is optional (but strongly recommended) 16

Predefined annotations @Deprecated marks API that programmers are discouraged from using replacement of the javadoc tag @deprecated if used => warning when compiled arguments String since default "" boolean forremoval default false 17

Predefined annotations @SuppressWarnings suppress warnings during compilation argument kinds of suppressed warnings String[] value supported kinds depend on a compiler always available kinds unchecked warning for improper usage of generics deprecation warning when deprecated elements are used e.g. @SuppressWarnings( unchecked ) @SuppressWarnings({ unchecked, deprecation ) 18

JAVA Lambda expressions 19

Motivation event handling in GUI a comparator implementation a thread implementation always an interface with a single method commonly using an anonymous inner class interface Comparator<T> { int compare(t o1, T o2); class Arrays {... void sort(t[] a, Comparator<T> c); Arrays.sort(array, new Comparator<AClass> () { public int compare(aclass o1, AClass o2) { return o1.x - o2.x; ); 20

Motivation the previous example using a lambda expression Arrays.sort(array, (o1, o2) -> o1.x - o2.x ); informally: an lambda expression ~ a block of code with parameters since Java 8 21

Functional interface where can be the lambda expressions use? where an object of an interface with a single abstract method is expected = functional interface a lambda expression = an instance of a functional interface but a lambda expression does not contain information about which functional interface it is implementing 22

Functional interface interface Predicate<T> { default Predicate<T> and(predicate<? super T> other); static <T> Predicate<T> isequal(object targetref); default Predicate<T> negate(); default Predicate<T> or(predicate<? super T> other); boolean test(t t); is it functional interface? yes only a single abstract method 23

Type of a lambda expression the same lambda expression can assigned to different interfaces Runnable r = () -> {; AutoCloseable r = () -> {; public interface Runnable { void run(); public interface AutoCloseable { void close(); 24

Type of a lambda expression lambda expressions are objects Runnable r = () -> {; Object o = r; but lambda expressions cannot be (directly) assigned to the Object type Object r = () -> {; as Object is not a functional interface 25

Lambda expression syntax a comma-separated list of parameters in parentheses types can be omitted since Java 11, var can be used parentheses can be omitted if there is only one parameter arrow -> body single expression return can be omitted no braces cannot be omitted if return is used block in curly braces 26

Examples of lambda expressions (int x, int y) -> x + y (x, y) -> x y (var x, var y) -> x y () -> 42 (String s) -> System.out.println(s) x -> 2 * x c -> { int s = c.size(); c.clear(); return s; 27

Functional interface @FunctionalInterface annotation to mark a functional interface usage is not mandatory similarly to @Override 28

References to methods String::valueOf a reference to a static method equivalent to: x -> String.valueOf(x) Object::toString a reference to a non-static method ekvivalent to: x -> x.tostring() x::tostring a reference a method of a particular object equivalent to: () -> x.tostring() ArrayList::new a reference to a constructor equivalent to: () -> new ArrayList<>() 29

Lambda expressions lambda expressions do not add a new scope of variable visibility Path first = Paths.get("/usr/bin"); Comparator<String> comp = (first, second) -> Integer.compare(first.length(), second.length()); this in a lambda expression refers to this of a method, in which the lambda expression is created public class Application { public void dowork() { Runnable runner = () -> {System.out.println(this.toString());; 30

Lambda expr. compilation public class AClass {... public void foo(aclass[] array) { Arrays.sort(array, new Comparator<AClass> () { public int compare(aclass o1, AClass o2) { return o1.x - o2.x; ); but public class AClass {... public void foo(aclass[] array) { Arrays.sort(array, (o1, o2) -> o1.x - o2.x);

JAVA java.lang.object 32

Methods clone equals finalize getclass hashcode notify notifyall tostring wait 33

equals boolean equals(object obj) be aware about the signature defined with the parameter type Object if overridden the parameter Object must be kept example class Complex { long x,y; public boolean equals(object obj) { if (obj instanceof Complex) { Complex c = (Complex) obj; if (c.x == x && c.y == y) { return true; return false; 34

equals ideal to declare the method with @Override @Override public boolean equals(object obj) if defined with another type, the method is overloaded but not overridden class Complex { long x,y; public boolean equals(complex obj) {... the class contains two method equals 35

hashcode int hashcode() hash code of the object used e.g. in the java.util.hashtable and others for the same object must always return the same value the value need not to be the same in different runs of a program if two objects are equals (by the equals method), then the hashcode must be the same value two different objects need not to have a different hashcode but it is desirable 36

clone Object clone() throws CloneNotSupportedException creates a copy of the object must hold x.clone()!= x should hold x.clone().equals(x) the class must implement the interface Cloneable otherwise the method throws CloneNotSupportedException arrays implement the Cloneable shallow copy of objects i.e. fields are not cloned for different behavior, the method should be overridden 37

clone overriding clone typical implementation but not mandatory protected Object clone() { Object clonedobj = super.clone();... return clonedobj; after cloning it holds: a.clone()!= a a.clone().equals(a) 38

tostring returns textual representation of an object default getclass().getname() + '@' + Integer.toHexString(hashCode()) should be overridden class MyClass {...... MyClass o = new MyClass(); System.out.println(o); // tostring() is called 39