Object-Oriented Programming



Similar documents
Java Interview Questions and Answers

Contents. 9-1 Copyright (c) N. Afshartous

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Chapter 13 - Inheritance

AP Computer Science Java Subset

Fundamentals of Java Programming

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

CS 111 Classes I 1. Software Organization View to this point:

Java Programming Language

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Java Programming Fundamentals

Java CPD (I) Frans Coenen Department of Computer Science

Java Application Developer Certificate Program Competencies

Part I. Multiple Choice Questions (2 points each):

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Chapter 1 Fundamentals of Java Programming

Inheritance, overloading and overriding

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

CS506 Web Design and Development Solved Online Quiz No. 01

Introduction to Java

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

java Features Version April 19, 2013 by Thorsten Kracht

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

D06 PROGRAMMING with JAVA

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Description of Class Mutation Mutation Operators for Java

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Introduction to Object-Oriented Programming

J a v a Quiz (Unit 3, Test 0 Practice)

Advanced OOP Concepts in Java

C++ INTERVIEW QUESTIONS

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Programming Languages CIS 443

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Moving from CS 61A Scheme to CS 61B Java

Java (12 Weeks) Introduction to Java Programming Language

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Lecture 5: Java Fundamentals III

Java SE 8 Programming

Chapter 1 Java Program Design and Development

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Computing Concepts with Java Essentials

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Glossary of Object Oriented Terms

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Explain the relationship between a class and an object. Which is general and which is specific?

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Java from a C perspective. Plan

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Basic Object-Oriented Programming in Java

History OOP languages Year Language 1967 Simula Smalltalk

Facebook Twitter YouTube Google Plus Website

Comp 411 Principles of Programming Languages Lecture 34 Semantics of OO Languages. Corky Cartwright Swarat Chaudhuri November 30, 20111

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Introduction to Java. CS 3: Computer Programming in Java

Using Inheritance and Polymorphism

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

ICOM 4015: Advanced Programming

Java Crash Course Part I

A Scala Tutorial for Java programmers

Web Development in Java

13 Classes & Objects with Constructors/Destructors

Programmation 2. Introduction à la programmation Java

Tutorial on Writing Modular Programs in Scala

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

public static void main(string[] args) { System.out.println("hello, world"); } }

Object-Oriented Programming in Java

A Comparison of the Object-Oriented Features of Ada 95 and Java

Programming Languages Featherweight Java David Walker

CSC 551: Web Programming. Fall 2001

Computer Programming I

The Interface Concept

An Overview of Java. overview-1

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Syllabus for CS 134 Java Programming

Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives

Stack Allocation. Run-Time Data Structures. Static Structures

CS193j, Stanford Handout #10 OOP 3

Schema Classes. Polyhedra Ltd

JAVA INTERVIEW QUESTIONS

Chapter 2 Introduction to Java programming

Transcription:

Object-Oriented Programming Classes Classes are syntactic units used to define objects. They may contain instance variables, which will occur in each instance of the class, instance methods, which can be executed by objects of the class, and constructors, which are called automatically when an object is created using new. Classes may also have class variables and class methods, but these belong to the class itself and have no direct effect on the objects. class MyClass private int value; MyClass(int n) value = n; void perform(int m) for (int k=1; k<=value; k++) System.out.print (m*k + " "); int compute() return value*value; Copyright 2004 by Ken Slonneger Object-Oriented Programming 1

Objects Objects are created from a class using the new operator, which invokes a constructor with matching parameter types. These objects may be assigned to variables declared of the type given by the class name. Each object has a copy of every instance variable in its class definition and in every superclass of that class. Instance methods in a class can be called only with an object of the class type (or a subclass). This object is called the receiver of the method and can be referred to by the keyword this inside of the method. MyClass first = new MyClass(5); MyClass second = new MyClass(3); first.perform(6); Prints: 6 12 18 24 30 second.perform(-4); Prints: -4-8 -12 2 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Constructors A constructor is a method that is called automatically when an object is created. If the programmer supplies no constructor, a default constructor with no parameters is provided. This default constructor disappears if the programmer writes one or more constructors in the class. In a constructor, this( ) calls another constructor of the same class with the given parameters and super( ) calls a constructor of its superclass with the given parameters. Another constructor for MyClass MyClass() this(10); Inheritance A new class can be defined as a subclass of an existing class using the extends keyword. Then every object of the new subclass will have copies of the instance variables from its superclass (and its superclass and so on) as well as its own instance variables. It can also call instance methods defined in its superclass as long as they are visible (not private). Any instance method in the superclass can be overridden (redefined) by writing a method in the subclass with the same signature. Copyright 2004 by Ken Slonneger Object-Oriented Programming 3

Any class definition without an extends clause is a subclass of Object by default. A variable of the superclass type may refer to an object of its class or an object of any of its subclasses (upcasting). If an overridden instance method is called on a variable of the superclass, the class of the object referred to determines which version of the overridden method will be executed. This property is known as polymorphism or dynamic binding. In an instance method, the identifier this refers to the object, the receiver, that is currently executing the instance method. The identifier super can be used to access instance methods (and variables) that have been overridden (and shadowed) in the subclass. class MySub extends MyClass private boolean okay; MySub(int n, boolean b) super(n); // assigns n to value, a private okay = b; // instance variable int compute() if (okay) return super.compute(); else return -1; What happens if we omit super in the definition of compute? 4 Object-Oriented Programming Copyright 2004 by Ken Slonneger

MyClass mc = new MyClass(33); MySub ms = new MySub(12, true); MyClass mcs = new MySub(-9, false); mc.perform(5) ms.perform(5) mc.compute() ms.compute() mcs.compute() calls parent method calls parent method calls parent method calls child method calls child method (polymorphism) Upcasting and Downcasting Upcasting refers to the mechanism in which an object from a subclass is assigned to a variable declared of the superclass type. No special operator is required since the subclass object "is-an" object of the superclass type automatically. Downcasting refers to the assignment of a superclass variable or the result from a function to a subclass variable, and it requires an explicit cast to the type of the subclass. Upcasting: mc = ms; mc = mcs; Downcasting: ms = (MySub)mcs; // legal only because mcs // refers to a MySub object Illegal downcast: ms = (MySub)mc; throws a ClassCastException Copyright 2004 by Ken Slonneger Object-Oriented Programming 5

Downcasting Assignment of a superclass variable or function result to a subclass variable; requires an explicit cast to the type of the subclass. A variable of a superclass type can be cast to a variable of a subclass type only if it refers to an object of that same subclass type. If the object referred to by the superclass variable is not an object of the subclass, a ClassCastException is thrown signaling an error. Upcasting and downcasting of object types also applies to parameter passing and to any situation where an object of one type is impersonating another class type. Polymorphism Example Define a collection of classes representing geometric solids and including a method for computing their volumes. The superclass provides a String instance variable for identification and a volume method to be overridden. class Solid private String kind; Solid(String k) kind = k; String getkind() return kind; double volume() return 0.0; // This code is never executed 6 Object-Oriented Programming Copyright 2004 by Ken Slonneger

class Sphere extends Solid private double radius; Sphere(double r) super("sphere"); radius = r; double volume() return 4.0/3.0*Math.PI*radius*radius*radius; class Cube extends Solid private double length; Cube(double g) super("cube"); length = g; double volume() return length*length*length; class Cone extends Solid private double radius, altitude; Cone(double r, double a) super("cone"); radius = r; altitude = a; Copyright 2004 by Ken Slonneger Object-Oriented Programming 7

double volume() return Math.PI*radius*radius*altitude/3.0; public class UseSolid public static void main(string [] args) Solid [] list = new Solid [6]; list[0] = new Cube(10); list[1] = new Cube(5); list[2] = new Sphere(10); list[3] = new Sphere(8); list[4] = new Cone(3, 5); list[5] = new Cone(8, 2); for (int k=0; k<list.length; k++) System.out.println(list[k].getKind() + " volume = " + list[k].volume()); /****************************************** % java UseSolid Cube volume = 1000.0 Cube volume = 125.0 Sphere volume = 4188.790204786391 Sphere volume = 2144.660584850632 Cone volume = 47.1238898038469 Cone volume = 134.0412865531645 ******************************************/ 8 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Abstract Classes The reserved word abstract can be used as a modifier for an instance method or a class. An abstract method has no body. It must be overridden in a subclass of its class to be made into a concrete, callable method. Any class with an abstract method must be declared as an abstract class, although any class can be made abstract using the modifier. An abstract class cannot be instantiated. It must be extended by a concrete subclass to create objects. Those objects may be assigned to a variable of the type of the abstract superclass (upcasting). abstract class Solid private String kind; Solid(String k) kind = k; String getkind() return kind; abstract double volume(); // Note semicolon Copyright 2004 by Ken Slonneger Object-Oriented Programming 9

The program UseSolid works exactly the same with this abstract class Solid. Interfaces An interface is a class-like unit that provides a specification of behavior (the syntax only) that classes must implement to make the behavior available. It contains only public instance method headers (no bodies) and public static final class variables. No objects can be instantiated directly from an interface. A class implements an interface by giving complete definitions of all of the methods in the interface. A variable declared of the interface type can be made to refer to an object of a class that implements the interface (upcasting). Polymorphism can be performed with a group of classes that implement a common interface. interface Printable void printnum(int n); // Automatically public and abstract 10 Object-Oriented Programming Copyright 2004 by Ken Slonneger

class FirstImpl implements Printable String name; FirstImpl(String s) name = s; public void printnum(int n) System.out.println(name + " prints " + n); class SecondImpl implements Printable int ID; SecondImpl(int n) ID = n; public void printnum(int n) System.out.println("Number" + ID + " prints " + n); FirstImpl fi = new FirstImpl("claude"); SecondImpl si = new SecondImpl(99); Printable [] pt = new Printable[2]; pt[0] = fi; pt[1] = si; Copyright 2004 by Ken Slonneger Object-Oriented Programming 11

for (int k=0; k<pt.length; k++) pt[k].printnum(20*k+5); Output claude prints 5 Number99 prints 25 The array could also be created using: Printable [] pt = fi, si ; Some Interfaces Defined in the Java API java.lang.cloneable java.lang.runnable java.util.iterator java.util.comparator java.lang.comparable java.io.datainput java.io.serializable java.awt.event.actionlistener Another Approach to Polymorphism Put the abstract method in an interface. Need to put the method getkind there also for polymorphism to work. interface Measurable String getkind(); double volume(); // Automatically public // Automatically public 12 Object-Oriented Programming Copyright 2004 by Ken Slonneger

abstract class Solid implements Measurable private String kind; Solid(String k) kind = k; public String getkind() return kind; class Sphere extends Solid private double radius; Sphere(double r) super("sphere"); radius = r; // public because of interface public double volume() // public because of interface return 4.0/3.0*Math.PI*radius*radius*radius; class Cube extends Solid class Cone extends Solid Copyright 2004 by Ken Slonneger Object-Oriented Programming 13

Consider another kind of object that has a volume. class Radio implements Measurable public String getkind() return "Radio"; public double volume() return 99.99; 14 Object-Oriented Programming Copyright 2004 by Ken Slonneger

public class UseSolid public static void main(string [] args) Measurable [] list = new Measurable [7]; list[0] = new Cube(10); list[1] = new Cube(5); list[2] = new Sphere(10); list[3] = new Sphere(8); list[4] = new Cone(3, 5); list[5] = new Cone(8, 2); list[6] = new Radio(); for (int k=0; k<list.length; k++) System.out.println(list[k].getKind() + " volume = " + list[k].volume()); /****************************************** % java UseSolid Cube volume = 1000.0 Cube volume = 125.0 Sphere volume = 4188.790204786391 Sphere volume = 2144.660584850632 Cone volume = 47.1238898038469 Cone volume = 134.0412865531645 Radio volume = 99.99 ******************************************/ Copyright 2004 by Ken Slonneger Object-Oriented Programming 15

Reference Types class array abstract class interface May refer to an object of that class or of one of its subclasses an array of the appropriate type an object of a concrete subclass of the abstract type an object of a class that implements the interface Variables of the reference types may have the value null or may refer to objects. The last two types cannot be instantiated. final The reserved word final can be used as a modifier for a class, for an instance method, or for a variable. A final class may not be subclassed (extended). A final instance method may not be overridden (turns off polymorphism). A final variable (any kind) must be initialized when declared and may not be subsequently altered. Exception: A final instance variable may be initialized in a constructor. 16 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Wrapper Classes Recall: The eight primitive types are not objects, for efficiency reasons boolean, char, byte, short, int, long, float, double Wrapper classes define objects, each of which encapsulates one unchangeable primitive value. Boolean, Character, Byte, Short, Integer, Long, Float, Double Wrapper classes found in package java.lang, which is visible to your program by default. Java Class Hierarchy Note: Number is an abstract class. Every object in Java is an Object. Copyright 2004 by Ken Slonneger Object-Oriented Programming 17

Purposes of Wrapper Classes Home for constants associated with the type. Home for class methods defined on values of the type. A way to treat primitive values as objects so they can be used by methods and classes that expect objects. Using Wrappers public class Wrap public static void main(string [] args) Object x = new Character('A'); checkout(x); x = new Double(99.999); checkout(x); x = new Boolean(false); checkout(x); x = new Integer(1109); checkout(x); 18 Object-Oriented Programming Copyright 2004 by Ken Slonneger

static void checkout(object ob) if (ob instanceof Double) Double d = (Double)ob; System.out.println("double value = " + d.doublevalue()); else if (ob instanceof Boolean) Boolean b = (Boolean)ob; System.out.println("boolean value = " + b.booleanvalue()); else if (ob instanceof Character) Character c = (Character)ob; System.out.println("char value = " + c.charvalue()); else if (ob instanceof Integer) System.out.println("int value = " + ((Integer)ob).intValue()); Output: char value = A double value = 99.999 boolean value = false int value = 1109 Copyright 2004 by Ken Slonneger Object-Oriented Programming 19

Integer Class public final class java.lang.integer extends java.lang.number // Fields public final static int MAX_VALUE; public final static int MIN_VALUE; // Constructors public Integer (int value); public Integer (String s); // Instance methods public byte bytevalue (); public short shortvalue (); public int intvalue (); public long longvalue (); public float floatvalue (); public double doublevalue (); public boolean equals (Object obj); public String tostring (); // Class methods public static int parseint (String s); public static String tostring (int i); public static Integer valueof (String s); Examples Integer m = new Integer("77"); Integer n = new Integer(77); m.intvalue() and n.intvalue() both return 77 20 Object-Oriented Programming Copyright 2004 by Ken Slonneger

m.tostring() and n.tostring() both return "77" m == n m.equals(n) returns false returns true Integer.MAX_VALUE returns 2147483647 Integer.valueOf("13") returns an Integer object Integer.valueOf("13").intValue() returns 13 Integer.parseInt("13") returns 13 Double.valueOf("4.5").doubleValue() Double.parseDouble("25.7") returns 4.5, a double returns 25.7, a double Integer.valueOf(str).intValue() new Integer(str).intValue() Integer.parseInt(str) Integer.toString(n) int n new Integer(n) num.intvalue() String str new Integer(str) Integer.valueOf(str) num.tostring() Integer num Copyright 2004 by Ken Slonneger Object-Oriented Programming 21

Exceptions What happens if we call Integer.parseInt("12e4")? The string cannot be parsed as an integer, so a runtime error occurs: java.lang.numberformatexception: 12e4 In Java, runtime errors are called exceptions. When such an error occurs, we say an exception has been thrown. Java has an extensive facility for handling exceptions, which are themselves objects. Command Line Arguments Java provides a mechanism for supplying command line arguments when a program is started. These arguments are treated as instances of String and are placed in the array specified as the formal parameter for the main method. Consider the following program: public class Args public static void main(string [] args) System.out.println("Number of args = " + args.length); for (int k=0; k<args.length; k++) System.out.println("Argument " + k + " = " + args[k]); 22 Object-Oriented Programming Copyright 2004 by Ken Slonneger

In a command line system, such as Unix, the program Args can be invoked using the format: % java Args one two 3 44 "this is number five" 666 Output Number of args = 6 Argument 0 = one Argument 1 = two Argument 2 = 3 Argument 3 = 44 Argument 4 = this is number five Argument 5 = 666 In early versions of CodeWarrior, the arguments were supplied in the Application window, as shown below: Copyright 2004 by Ken Slonneger Object-Oriented Programming 23

Kinds of Identifiers 1. Module (collection of definitions) identifiers Class Package Interface 2. Method identifiers Class methods Instance methods Constructors 3. Variable identifiers Class variables Instance variables Local variables Method parameters (constructor parameters) Exception handler parameters 24 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Scope (Visibility) of Identifiers 1. Class scope The entire class (at least) Class methods Instance methods (and constructors) Class variables (including constants) Instance variables Order of these declarations makes no difference with one exception. int m = n; int n = 5; // is illegal (also for static) These variables are automatically initialized to default values unless they are final (constants). 2. Block scope (method scope) Method parameters: Entire method. Local variables: Point of declaration to the end of the block (method). Block command: // declarations and commands Local variable declarations may hide class and instance variables, but not other local variables: local variables may not be hidden in inner scopes. Copyright 2004 by Ken Slonneger Object-Oriented Programming 25

Inner Classes All of the classes defined by us so far have been top-level classes, meaning that they lie at the top level of packages and files. As a consequence, names of classes and their members must be visible to all classes in a package or to none at all. Inner classes allow us to restrict visibility by making a class local to another class or to a method. An inner class may be defined inside: 1. Another class. 2. A method (a block). 3. An expression (using an anonymous class). Each object created from an inner class is associated with an object created from the class in which it is defined. Inner classes may not have static members. The name of an inner class must be different from the names of all of its enclosing classes. 26 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Example Define a class, Chief, whose objects have an int value as their state with an instance method that can alter the value. Define a second class, Helper, whose objects are responsible for printing the values stored in Chief objects. Each instance of Helper contains a reference to the Chief object that it is responsible for. A Helper object can be created either by using A Helper constructor directly or An instance method mkhelper in Chief (a factory method). The system is tested by a main method in a third class, called ChiefTest, that creates two Chief objects and two associated Helper objects. class Chief int value; // should be private Chief(int n) value = n; void alter() value = 2*value+10; Helper mkhelper() // must be an instance method return new Helper(this); Copyright 2004 by Ken Slonneger Object-Oriented Programming 27

class Helper private Chief chf; Helper(Chief c) chf = c; void showvalue() System.out.println(chf.value); public class ChiefTest public static void main(string [] args) Chief a = new Chief(5); Chief b = new Chief(8); Helper ahelp = a.mkhelper(); Helper bhelp = new Helper(b); ahelp.showvalue(); a.alter(); ahelp.showvalue(); bhelp.showvalue(); b.alter(); bhelp.showvalue(); Output 5 8 20 26 28 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Drawbacks The state variable in Chief cannot be private. Each Helper object needs to maintain an explicit reference to the Chief object that it is associated with. The following version solves the same problem using an inner class for Helper. class Chief private int value; //---- Inner Class --------------------------- class Helper void showvalue() System.out.println(value); //------------------------------------------------ Chief(int n) value = n; void alter() value = 2*value+10; Helper mkhelper() return new Helper(); // must be an instance method // Return an instance of Helper whose // enclosing instance will be this. Copyright 2004 by Ken Slonneger Object-Oriented Programming 29

public class ChiefTestInner public static void main(string [] args) Chief a = new Chief(5); Chief b = new Chief(8); Helper ahelp = a.mkhelper(); // Get a Helper object enclosed by a s object. Helper bhelp = b.new Helper(); // Get a Helper object enclosed by b s object. // Note the new syntax for new. ahelp.showvalue(); bhelp.showvalue(); a.alter(); b.alter(); ahelp.showvalue(); bhelp.showvalue(); Each Helper object has an implicit reference to the object for which it was created. Writing b.new Helper() builds a Helper object associated with b. Scoping Properties All identifiers in Chief are visible inside of Helper. All identifiers in Helper are visible inside of Chief. Helper cannot be accessed from outside of Chief because it is declared private. 30 Object-Oriented Programming Copyright 2004 by Ken Slonneger

a ahelp b bhelp Anonymous Classes Anonymous classes (classes with no name) may appear in expressions that expect a class item following a new operator. Syntax of a new expression with an anonymous class: new SuperType(constructor parameters) instance methods and instance variables of inner class The SuperType may be: 1. A class: Then the anonymous class extends SuperType, and the parameters are for a call to a superclass constructor. 2. An interface: Then the anonymous class implements SuperType (and extends Object), and there can be no constructor parameters. Copyright 2004 by Ken Slonneger Object-Oriented Programming 31

Observation Since an anonymous class has no name, it cannot have an explicit constructor only the default constructor provided by Java is available. Note Difference Domino d = new Domino(2,2,true); Domino e = new Domino(2,2,true) public String tostring() return getlow() + "--" + gethigh(); ; // semicolon required at end of a declaration The addition of inner classes to Java requires no change in the Java virtual machine. The compiler translates all inner classes into regular Java classes. Java also has static inner classes, called nested classes. These classes are not associated with objects and are of little use in OOP. 32 Object-Oriented Programming Copyright 2004 by Ken Slonneger

Using an Anonymous Classes Suppose we want to create another implementation of the interface Printable. This implementation will only be used once. Change the code as follows. Printable [] pt = new Printable[3]; pt[0] = fi; pt[1] = si; pt[2] = new Printable() public void printnum(int n) System.out.println(">>>" + n + "<<<"); ; for (int k=0; k<pt.length; k++) pt[k].printnum(20*k+5); Output claude prints 5 Number99 prints 25 >>>45<<< Copyright 2004 by Ken Slonneger Object-Oriented Programming 33

Member Visibility Use the term "member" for a variable or a method in a class. Visibility depends on the modifier on the class as well as the modifier on the member. Same class Other class same package Subclass other package Any class public class public member Yes Yes Yes Yes protected member Yes Yes Yes member Yes Yes private member Yes class public member Yes Yes protected member Yes Yes member Yes Yes private member Yes private class (an inner class) Enclosing class public member Yes Yes protected member Yes Yes member Yes Yes private member Yes Yes 34 Object-Oriented Programming Copyright 2004 by Ken Slonneger