Timing for Interfaces and Abstract Classes

Similar documents
Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Exercise. Zheng-Liang Lu Java Programming 273 / 324

Another IS-A Relationship

Interfaces. An interface forms a contract between the object and the outside world.

enum Types 1 1 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 267 / 287

Interfaces (1/2) An interface forms a contract between the object and the outside world.

A final method is a method which cannot be overridden by subclasses. A class that is declared final cannot be inherited.

Subtype Polymorphism

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Method Overriding. Note that you can invoke the overridden method through the use of the keyword super.

Java Programming 2. Zheng-Liang Lu. Java2 304 Fall Department of Computer Science & Information Engineering National Taiwan University

CS 251 Intermediate Programming More on classes

Java Programming 2. Zheng-Liang Lu. Java2 306 Fall Department of Computer Science & Information Engineering National Taiwan University

Packages Inner Classes

Enumerated Types. CSE 114, Computer Science 1 Stony Brook University

Introduction to Programming Using Java (98-388)

COMP-202: Foundations of Programming. Lecture 8: for Loops, Nested Loops and Arrays Jackie Cheung, Winter 2016

Programming overview

Object Orientation Fourth Story. Bok, Jong Soon

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

CMSC 132: Object-Oriented Programming II

Objectives. Describe ways to create constants const readonly enum

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

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Cloning Enums. Cloning and Enums BIU OOP

1 Shyam sir JAVA Notes

Reflection. Based on

Java Fundamentals (II)

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Topic 6: Inner Classes

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Lecture 2: Java & Javadoc

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

CSC-140 Assignment 6

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

Chapter 4 Java Language Fundamentals

A foundation for programming. Classes and objects. Overview. Java primitive types. Primitive types Creating your own data types

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Topic 5: Enumerated Types and Switch Statements

Short Notes of CS201

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CS201 - Introduction to Programming Glossary By

CITS2210 Object-Oriented Programming. Topic 10. Java: Nested and Inner Classes

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

LTBP INDUSTRIAL TRAINING INSTITUTE

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Objects and Iterators

Java Programming Training for Experienced Programmers (5 Days)

9 Working with the Java Class Library

CO Java SE 8: Fundamentals

JavaScript: Sort of a Big Deal,

Computer Science II (20082) Week 1: Review and Inheritance

Java: introduction to object-oriented features

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Index COPYRIGHTED MATERIAL

Inheritance and Interfaces

OVERRIDING. 7/11/2015 Budditha Hettige 82

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

Outline. Java Compiler and Virtual Machine. Why Java? Naming Conventions. Classes. COMP9024: Data Structures and Algorithms

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

Swing: Building GUIs in Java

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

Swing: Building GUIs in Java

CLASSES AND OBJECTS. Fundamentals of Computer Science I

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Example: Count of Points

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

The Essence of OOP using Java, Nested Top-Level Classes. Preface

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Java Programming Course Overview. Duration: 35 hours. Price: $900

More Relationships Between Classes

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

PROGRAMMING FUNDAMENTALS

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Lab5. Wooseok Kim

Instance Members and Static Members

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

CMSC 132: Object-Oriented Programming II

Java 8 Programming for OO Experienced Developers

Java Threads and intrinsic locks

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Expressions & Flow Control

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

From C++ to Java. Duke CPS

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Data Types. 1 You cannot change the type of the variable after declaration. Zheng-Liang Lu Java Programming 52 / 87

Chapter 4 Defining Classes I

Formatting Output & Enumerated Types & Wrapper Classes

Transcription:

Timing for Interfaces and Abstract Classes Consider using abstract classes if you want to: share code among several closely related classes declare non-static or non-final fields Consider using interfaces for any of situations as follows: unrelated classes would implement your interface specify the behavior of a particular data type, but not concerned about who implements its behavior take advantage of multiple inheritance Zheng-Liang Lu Java Programming 292 / 323

Wrapper Classes To treat values as objects, Java supplies standard wrapper classes for each primitive type. For example, you can construct a wrapper object from a primitive value or from a string representation of the value. 1... 2 Double pi = new Double("3.14"); 3... Zheng-Liang Lu Java Programming 293 / 323

Zheng-Liang Lu Java Programming 294 / 323

Autoboxing and Unboxing of Primitives The Java compiler automatically wraps the primitives in their wrapper types, and unwraps them where appropriate. 1... 2 Integer i = 1; // autoboxing 3 Integer j = 1; 4 System.out.println(i + j); // unboxing; output 2 5 6 System.out.println(i == j); // output true 7 System.out.println(i.equals(j)); // output true 8... The method equals() inherited from Object is used to compare the contents of two objects. Herein, the values of wrapper objects. Zheng-Liang Lu Java Programming 295 / 323

Immutable Objects An object is considered immutable if its state cannot change after it is constructed. Often used for value objects. Imagine that there is a pool for immutable objects. After the value object is first created, this value object is reused if needed. This implies that another object is created when we operate on the immutable object. Zheng-Liang Lu Java Programming 296 / 323

For example, 1... 2 k = new Integer(1); 3 System.out.println(i == k); // output false (why?) 4 System.out.println(k.equals(i)); // output true 5 6 Integer q = 2; 7 i++; 8 System.out.println(i == q); // output true 9 System.out.println(i.equals(q)); // output true 10... Good practice when it comes to concurrent programming. 1 Another example is String objects. 1 See http://www.javapractices.com/topic/topicaction.do?id=29. Zheng-Liang Lu Java Programming 297 / 323

enum Types 2 An enum type is an reference type limited to an explicit set of values. An order among these values is defined by their order of declaration. There exists a correspondence with string names identical to the name declared. 2 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 298 / 323

Example 1... 2 enum Weekday {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday} 3... Actually, Weekday is a subclass of enum type with seven static and final objects corresponding to the seven enumerated values. The Weekday instances which really exist are the seven enumerated values. So this mechanism enhances type safety! Zheng-Liang Lu Java Programming 299 / 323

1 public class EnumerationDemo { 2 public static void main(string[] args) { 3 Weekday[] weekdays = Weekday.values(); 4 // The method values() returns a Weekday array. 5 6 for (Weekday day: weekdays) { 7 System.out.println(day); 8 } 9 10 Weekday today = Weekday.Sunday; 11 Weekday tomorrow = Weekday.Monday; 12 13 System.out.println(today == tomorrow); // output false 14 } 15 } Zheng-Liang Lu Java Programming 300 / 323

Exercise: Colors 1 enum Color { 2 3 Red, Green, Blue; // three options 4 5 static Color randomcolor() { 6 Color[] colorset = values(); 7 int pickonecolor = (int) (Math.random() colorset. length); 8 return colorset[pickonecolor]; 9 } 10 } 11 12 public class EnumDemo { 13 public static void main(string[] args) { 14 for(int i = 1 ; i <= 3; i++) 15 System.out.println(Color.randomColor()); 16 } 17 } Zheng-Liang Lu Java Programming 301 / 323

Exercise: Size 1 enum Size { 2 3 Large("L"), Medium("M"), Small("S"); 4 5 private String abbr; 6 private Size(String abbr) { this.abbr = abbr; } 7 8 public String getabbr() { 9 return this.abbr; 10 } 11 } 12 13 public class EnumDemo { 14 public static void main(string[] args) { 15 System.out.println(Size.Small.getAbbr()); // output S 16 } 17 } Zheng-Liang Lu Java Programming 302 / 323

Packages We bundle groups of related types into packages for the following 3 purposes: To make types easier to find and use To avoid naming conflicts To control access Note that types refers to classes, interfaces, and enumerations. For example, fundamental classes are in java.lang and classes for I/O are in java.io. Zheng-Liang Lu Java Programming 303 / 323

Access Control Scope \ Modifier private (default) protected public Within the class Within the package x Inherited classes x x Out of package x x x Zheng-Liang Lu Java Programming 304 / 323

Nested Classes A nested class is a member of its enclosing class. Non-static nested classes, aka inner classes, have access to other members of the enclosing class, even if they are declared private. Instead, static nested classes do not have access to other instance members of the enclosing class. Timing of usage: Logically grouping classes that are only used in one place Increasing encapsulation Leading to more readable and maintainable code Zheng-Liang Lu Java Programming 305 / 323

Family of Nested Classes Zheng-Liang Lu Java Programming 306 / 323

Inner Classes Inner classes are of three types depending on how and where you define them. Inner class Method-local inner class Anonymous inner class All cannot define or declare any static members. Unlike a normal class, an inner class can be declared private. Once an inner class is declared private, it cannot be accessed from an object outside the class. Note that the creation of inner type objects is available after the outer type object is created. In other words, you cannot invoke the constructor of the inner type without having the outer type object. Zheng-Liang Lu Java Programming 307 / 323

Example: Inner Class 1 class OuterClass { 2 private int x = 1; 3 InnerClass innerclassinstance = new InnerClass(); 4 5 class InnerClass { 6 public void print() { 7 System.out.println(x); 8 } 9 } 10 } 11 12 public class InnerClassDemo { 13 public static void main(string[] args) { 14 OuterClass outer = new OuterClass(); 15 outer.innerclassinstance.print(); 16 17 InnerClass inner = new InnerClass(); // oops 18 // Since InnerClass type cannot be resolved out of OuterClass. 19 } 20 } Zheng-Liang Lu Java Programming 308 / 323

Example: Method-local Inner Class 1 class OuterClass { 2 private int x = 1; 3 4 void outerclassmethod() { 5 class MLInnerClass { 6 int y = 2; 7 static int z = 3; // implicitly final 8 9 void print() { 10 System.out.println(x); 11 System.out.println(y); 12 System.out.println(z); 13 } 14 } 15 16 MLInnerClass MLInnerClassInstance = new MLInnerClass(); 17 MLInnerClassInstance.print(); 18 } 19 } Zheng-Liang Lu Java Programming 309 / 323

Anonymous Inner Class Anonymous inner classes are an extension of the syntax of the new operation, enabling you to declare and instantiate a class at the same time. However, these do not have a name. Use them when you need to use these types only once. An anonymous class cannot define any static fields, methods, and classes, except for static final constants. Zheng-Liang Lu Java Programming 310 / 323

Example 1 abstract class A { 2 void foo(); 3 } 4 5 public class AnonymousClassDemoOne { 6 public static void main(string[] args) { 7 A a = new A() { 8 public void foo() { / different implementation / } 9 void othermethods() {} 10 }; 11 12 a.foo(); 13 } 14 } Since there is no definition of othermethods() in A, a.othermethods() is not allowed. Zheng-Liang Lu Java Programming 311 / 323

Exercise 1 interface B { 2 void foo(); 3 } 4 5 public class AnonymousClassDemoTwo { 6 public static void main(string[] args) { 7 B b = new B() { 8 public void foo() { / different implementation / } 9 }; 10 11 b.foo(); 12 } 13 } An interface can be used to instantiate an object indirectly by anonymous classes with implementing the abstract methods. Zheng-Liang Lu Java Programming 312 / 323

Iterators An important use of inner classes is to define an adapter class as a helper object. Using adapter classes, we can write classes more naturally, without having to anticipate every conceivable user s needs in advance. Instead, you provide adapter classes that marry your class to a particular interface. For example, an iterator is a simple and standard interface to enumerate objects in many data structures. The java.util.iterator interface defines two methods: public boolean hasnext() and public Object next(). Zheng-Liang Lu Java Programming 313 / 323

Example: An Iterator 1 class EmployeeRepository { 2 private Employee[] employees; 3 4 EmployeeRepository(Employee... inputlist) { 5 employees = inputlist; 6 } 7 private Iterator iter = new Iterator() { 8 int num = 0; 9 public boolean hasnext() { 10 return num < employees.length; 11 } 12 public Object next() { 13 return hasnext()? employees[num++] : null; 14 } 15 }; 16 void list() { 17 while (this.iter.hasnext()) { 18 System.out.println(this.iter.next()); 19 } 20 } 21 } Zheng-Liang Lu Java Programming 314 / 323

1 abstract class Employee {} 2 class CEO extends Employee { 3 public String tostring() { 4 return "CEO"; 5 } 6 } 7 class Manager extends Employee { 8 public String tostring() { 9 return "Manager"; 10 } 11 } 1 import java.util.iterator; 2 3 public class IteratorDemo { 4 public static void main(string[] args) { 5 EmployeeRepository x; 6 x = new EmployeeRepository(new CEO(), new Manager()); 7 x.list(); 8 } 9 } Zheng-Liang Lu Java Programming 315 / 323

Lambda Expressions Lambda expressions allow small bits of code to be written inline as literals and facilitate a more functional style of programming Java. Since Java SE 8, lambda expressions are used to replace anonymous inner classes. You can find a detailed tutorial for lambda expressions from http://www.oracle.com/webfolder/technetwork/ tutorials/obe/java/lambda-quickstart/. Check the example using the Function interface. Read https://docs.oracle.com/javase/tutorial/java/ javaoo/lambdaexpressions.html. If you are interested in the origin of Lambda expressions, read https://en.wikipedia.org/wiki/lambda_calculus. Zheng-Liang Lu Java Programming 316 / 323

Example 1 public class LambdaExpressionDemo { 2 3 public static void main(string[] args) { 4 Runnable r1 = new Runnable() { 5 public void run() { 6 System.out.println("R1..."); 7 } 8 }; 9 10 Runnable r2 = () > System.out.println("R2..."); 11 12 r1.run(); 13 r2.run(); 14 } 15 } Zheng-Liang Lu Java Programming 317 / 323

Static Nested Class A static inner class is a nested class which is a static member of the outer class. So they can access to other static members without instantiating the outer class. Just like static members, a static nested class does not have access to the instance members of the outer class. Most important, a static nested class can be instantiated directly, without instantiating the outer class object first. Static nested classes act something like a minipackage. Zheng-Liang Lu Java Programming 318 / 323

Example 1 class OuterClass { 2 static int x = 1; 3 int y = 2; 4 5 void OuterClassMethod() { 6 System.out.println(y); 7 } 8 9 static class StaticNestedClass { 10 int z = 3; 11 void StaticNestedClassMethod() { 12 System.out.println(x); 13 System.out.println(y); // Oops, static members cannot access to instance members. 14 System.out.println(z); 15 } 16 } 17 } Zheng-Liang Lu Java Programming 319 / 323

1 public class StaticNestedClassDemo { 2 public static void main(string[] args) { 3 OuterClass.StaticNestedClass x = new OuterClass. StaticNestedClass(); 4 x.staticnestedclassmethod(); 5 } 6 } Zheng-Liang Lu Java Programming 320 / 323

Classpath 3 The variable classpath is a environment variable for the Java compiler to specify the location of user-defined classes and packages. By default, only the packages of the JDK standard API and extension packages are accessible without needing to set where to find them. The path for all user-defined packages and libraries must be set in the command-line (or in the Manifest associated with the JAR file containing the classes). 3 https://en.wikipedia.org/wiki/classpath_(java) Zheng-Liang Lu Java Programming 321 / 323

Usage of Classpath You may use the following command in any terminal: java -cp [the absolute path of the classes or packages] [the full name of the application to run] For Windows users, try java -cp c:\workspace\project train.java.helloworld On Linux/Unix/Mac OS users, try java -cp /workspace/project train.java.helloworld Zheng-Liang Lu Java Programming 322 / 323

Java Archive (JAR) 5 JAR is a packed format typically used to aggregate many Java class files, associated metadata 4 and resources (text, images, etc.) into one file to distribute the application software or libraries running on the Java platform. Try an executable JAR! 4 Metadata refers data of data. 5 See https://docs.oracle.com/javase/tutorial/deployment/jar/. Zheng-Liang Lu Java Programming 323 / 323