Exercise. Zheng-Liang Lu Java Programming 273 / 324

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

Timing for Interfaces and Abstract Classes

Another IS-A Relationship

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.

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

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

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

Interfaces (1/2) 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

More Relationships Between Classes

First IS-A Relationship: Inheritance

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

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

Exercise: Singleton 1

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

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

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

Example: Count of Points

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

Example: Count of Points

Lecture 2: Java & Javadoc

Introduction to Programming Using Java (98-388)

Java Fundamentals (II)

1 Shyam sir JAVA Notes

PROGRAMMING III OOP. JAVA LANGUAGE COURSE

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

CS 251 Intermediate Programming More on classes

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java: introduction to object-oriented features

OVERRIDING. 7/11/2015 Budditha Hettige 82

Instance Members and Static Members

Object Orientation Fourth Story. Bok, Jong Soon

CS111: PROGRAMMING LANGUAGE II

Programming overview

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

Packages Inner Classes

Inheritance and Interfaces

Compaq Interview Questions And Answers

Java 8 Programming for OO Experienced Developers

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

CMSC 132: Object-Oriented Programming II

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Objectives. Describe ways to create constants const readonly enum

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

a guide to an object oriented programming language Niket Sheth JAVA

Java Object Oriented Design. CSC207 Fall 2014

CS260 Intro to Java & Android 03.Java Language Basics

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

What is Inheritance?

Inheritance and Polymorphism

Chapter 6 Introduction to Defining Classes

CMSC 132: Object-Oriented Programming II

Index COPYRIGHTED MATERIAL

Java How to Program, 8/e

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

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Object-Oriented Programming

OBJECT ORİENTATİON ENCAPSULATİON

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CO Java SE 8: Fundamentals

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

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

Inheritance (Outsource: )

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

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

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Inheritance (continued) Inheritance

WA1278 Introduction to Java Using Eclipse

CISC370: Inheritance

Chapter 5 Object-Oriented Programming

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

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

CS-202 Introduction to Object Oriented Programming

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Cloning Enums. Cloning and Enums BIU OOP

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Inheritance and Polymorphism

Object Oriented Programming

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

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

JavaScript: Sort of a Big Deal,

LTBP INDUSTRIAL TRAINING INSTITUTE

The Java Programming Language

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

COP 3330 Final Exam Review

Practice for Chapter 11

Chapter 4 Java Language Fundamentals

CH. 2 OBJECT-ORIENTED PROGRAMMING

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

9 Working with the Java Class Library

Transcription:

Exercise Zheng-Liang Lu Java Programming 273 / 324

1 public class AnimalFamilyDemo { 2 public static void main(string[] args) { 3 Dog d = new Dog(); 4 d.sleep(); 5 d.eat(); 6 d.watchdoor(); 7 8 Animal a = d; // upcasting 9 a.sleep(); 10 a.eat(); 11 a.watchdoor(); // oops, invisible! 12 a.chaselittlething(); // oops, invisible! 13 14 d = (Dog) a; // downcasting 15 d.watchdoor(); // works! 16 } 17 } Zheng-Liang Lu Java Programming 274 / 324

Field Hiding with Polymorphism You can refer to hidden fields simply by casting an object to a variable of the appropriate superclass. 1 class T { 2 int x = 1; 3 } 4 5 class U extends T { 6 int x = 2; 7 } 8 9 public class FieldHidingDemo { 10 public static void main(string[] args) { 11 U u = new U(); 12 System.out.println(u.x); // output 2 13 T t = u; 14 System.out.println(t.x); // output 1 15 } 16 } Zheng-Liang Lu Java Programming 275 / 324

Method Overriding with Polymorphism However, you cannot invoke overridden methods by upcasting. JVM calls the appropriate method for the object. Method lookup starts from the bottom of the class hierarchy to the top. Always looking for the most specific method body. These methods are referred to as virtual methods. This mechanism preserves the behaviors of the objects and the superclass type variables play the role of placeholders. Zheng-Liang Lu Java Programming 276 / 324

Example Imagine that we have a zoo with some animals. 1 class Animal { 2 void speak() {} 3 } 4 5 class Dog extends Animal { 6 void speak() { 7 System.out.println("woof"); 8 } 9 } 10 11 class Cat extends Animal { 12 void speak() { 13 System.out.println("meow"); 14 } 15 } 16 17 class Bird extends Animal { 18 void speak() { 19 System.out.println("tweet"); Zheng-Liang Lu Java Programming 277 / 324

20 } 21 } 22 23 public class PolymorphismDemo { 24 public static void main(string[] args) { 25 Animal[] zoo = {new Dog(), new Cat(), new Bird()}; 26 for (Animal a: zoo) { 27 a.speak(); 28 } 29 } 30 } Zheng-Liang Lu Java Programming 278 / 324

The final Keyword A final variable is a variable which can be initialized once and cannot be changed later. The compiler makes sure that you can do it only once. A final variable is often declared with static keyword and treated as a constant, for example, Math.PI. A final method is a method which cannot be overridden by subclasses. You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object. A class that is declared final cannot be inherited. Zheng-Liang Lu Java Programming 279 / 324

1 class A { 2 final int x = 1; 3 Example 4 final void foo() { 5 x = x + 1; // oops, you cannot change a final variable 6 System.out.println("old foo"); 7 } 8 } 9 10 final class B extends A { 11 int y = 2; 12 13 // cannot be overrided 14 void foo() { 15 System.out.println("my new foo"); 16 } 17 } 18 19 class C extends B {} // oops, B cannnot be inherited 20 21 22 Zheng-Liang Lu Java Programming 280 / 324

23 public class FinalKeywordDemo { 24 public static void main(string[] args) { 25 26 final B b = new B(); 27 System.out.println(b.x); // output 1 28 b.foo(); 29 30 b.y = 3; // ok 31 b = new B(); // oops, cannot reference to a new object 32 } 33 } Zheng-Liang Lu Java Programming 281 / 324

Abstract Class An abstract class is a class declared abstract. The classes that sit at the top of an object hierarchy are typically abstract classes. 1 These abstract class may or may not have abstract methods, which are methods declared without implementation. More explicitly, the methods are declared without braces, and followed by a semicolon. If a class has one or more abstract methods, then the class itself must be declared abstract. All abstract classes cannot be instantiated. Moreover, abstract classes act as placeholders for the subclass objects. 1 The classes that sit near the bottom of the hierarchy are called concrete classes. Zheng-Liang Lu Java Programming 282 / 324

Example Abstract methods and classes are in italic. In this example, the abstract method draw() and resize() should be implemented depending on the real shape. Zheng-Liang Lu Java Programming 283 / 324

Another IS-A Relationship Not all classes share a vertical relationship. Instead, some are supposed to perform the specific methods without a vertical relationship. Consider the class Bird inherited from Animal and Airplane inherited from Transportation. Both Bird and Airplane are able to be in the sky. So they should perform the method canfly(), for example. By semantics, the method canfly() could not be defined in their superclasses. We need a horizontal relationship. Zheng-Liang Lu Java Programming 284 / 324

Example 1 interface Flyable { 2 void canfly(); // public + abstract 3 } 4 5 abstract class Animal {} 6 7 class Bird extends Animal implements Flyable { 8 public void canfly() { 9 System.out.println("Bird flying..."); 10 } 11 } 12 13 abstract class Transportation {} 14 15 class Airplane extends Transportation implements Flyable { 16 public void canfly() { 17 System.out.println("Airplane flying..."); 18 } 19 } Zheng-Liang Lu Java Programming 285 / 324

1 public class interfacedemo { 2 public static void main(string[] args) { 3 Airplane a = new Airplane(); 4 a.canfly(); 5 6 Bird b = new Bird(); 7 b.canfly(); 8 9 Flyable f = a; 10 f.canfly(); // output Airplane flying... 11 f = b; 12 f.canfly(); // output Bird flying... 13 } 14 } Zheng-Liang Lu Java Programming 286 / 324

Interfaces An interface forms a contract between the object and the outside world. For example, the buttons on the television set are the interface between you and the electrical wiring on the other side of its plastic casing. An interface is also a reference type, just like classes, in which only method signatures are defined. So they can be the types of reference variables! Note that interfaces cannot be instantiated (directly). A class implementing one or multiple interfaces provides method bodies for each defined method signature. This allows a class to play different roles, with each role providing a different set of services. Zheng-Liang Lu Java Programming 287 / 324

Example Zheng-Liang Lu Java Programming 288 / 324

1 interface Driveable { 2 void startengine(); 3 void stopengine(); 4 void accelerate(); 5 void turn(); 6 } 1 class Automobile implements Driveable { 2 public void startengine() {... } 3... // and so on 4 public void honkhorn() {... } 5... 6 } 7 8 class Lawnmower implements Driveable { 9 public void startengine() {... } 10... // and so on 11 public void cutgrass() {... } 12... 13 } Zheng-Liang Lu Java Programming 289 / 324

Properties of Interfaces The methods of an interface are implicitly public. In most cases, the class which implements the interface should implement all the methods defined in the interface. Otherwise, the class should be abstract. An interface can declare only fields which are static and final. You can also define static methods in the interface. A new feature since Java SE 8 allows to define the methods with implementation in the interface. A method with implementation in the interface is declared default. Zheng-Liang Lu Java Programming 290 / 324

An interface can extend another interface, just like a class which can extend another class. However, an interface can extend many interfaces as you need. For example, Driveable and Updateable are good interface names. Common interfaces are Runnable 2, Serializable 3, and Collection 4. 2 Related to multithreading. 3 Aka object serialization where an object can be represented as a sequence of bytes that includes the object s data as well as information about the object s type and the types of data stored in the object. 4 Collections are data structures that are fundamental to all types of programming. Zheng-Liang Lu Java Programming 291 / 324

Timing for Interfaces and Abstract Classes Consider using abstract classes if any of these statements apply to your situation: share code among several closely related classes declare non-static or non-final fields Consider using interfaces if any of these statements apply to your situation: 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 / 324

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 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 293 / 324

Zheng-Liang Lu Java Programming 294 / 324

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 / 324

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 / 324

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. 5 Another example is String objects. 5 See http://www.javapractices.com/topic/topicaction.do?id=29. Zheng-Liang Lu Java Programming 297 / 324

enum Types 6 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. 6 The keyword enum is a shorthand for enumeration. Zheng-Liang Lu Java Programming 298 / 324

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 / 324

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 / 324

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 / 324

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

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 / 324

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 / 324

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 / 324

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

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 / 324

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 / 324

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 / 324

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 / 324

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 void foo() {} 9 void hoo() {} 10 }; 11 12 a.foo(); 13 a.hoo(); // oops 14 } 15 } Since there is no definition of hoo() in A, a.hoo() is not allowed. Zheng-Liang Lu Java Programming 311 / 324

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() {} 9 void hoo() {} 10 }; 11 12 y.foo(); 13 y.hoo(); // oops 14 } 15 } An interface can be used to instantiate an object indirectly by anonymous classes with implementing the abstract methods. Zheng-Liang Lu Java Programming 312 / 324

Adapters An important use of inner classes is to define an adapter class as a helper. 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. The java.util.iterator interface defines two methods: public boolean hasnext() and public Object next(). Zheng-Liang Lu Java Programming 313 / 324

Example: An Iterator 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 public class IteratorDemo { 2 public static void main(string[] args) { 3 EmployeeRepository x; 4 x = new EmployeeRepository(new CEO(), new Manager()); 5 x.list(); 6 } 7 } Zheng-Liang Lu Java Programming 314 / 324

1 import java.util.iterator; 2 3 class EmployeeRepository { 4 private Employee[] employees; 5 6 EmployeeRepository(Employee...inputList) { 7 employees = inputlist; 8 } 9 10 private Iterator iter = new Iterator() { 11 int num = 0; 12 13 public boolean hasnext() { 14 return num < employees.length; 15 } 16 17 public Object next() { 18 if (hasnext()) { 19 return employees[num++]; 20 } else { 21 return null; 22 } 23 } 24 }; Zheng-Liang Lu Java Programming 315 / 324

25 26 void list() { 27 while (this.iter.hasnext()) { 28 System.out.println(this.iter.next()); 29 } 30 } 31 } Zheng-Liang Lu Java Programming 316 / 324

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 317 / 324

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 318 / 324

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 319 / 324

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 320 / 324

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 321 / 324

Classpath 7 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). 7 https://en.wikipedia.org/wiki/classpath_(java) Zheng-Liang Lu Java Programming 322 / 324

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 323 / 324

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