20
Copyright @ 2000 Jordan Anastasiade. All right s reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and Inner Classes. Interface. Packages in Java. Using multiple classes, packages in Java files.

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Embed Size (px)

Citation preview

Page 1: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1

Class

In this lesson you will be learning about:

Class.

Inheritance.

Polymorphism.

Nested and Inner Classes.

Interface.

Packages in Java.

Using multiple classes, packages in Java files.

Page 2: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 2

Creating Classes

The fundamental unit of programming in Java is class.

public class Sphere { static final double PI = 3.14; double radius; Point3D center; public Sphere(double r, Point3D c) {

radius = r; center = c; } double volume() {

double v = 4.0/3.0 * PI;return v * radius*radius*radius;

}}

Class Declaration

Class Body

Constructor

Method

Fields

1

Modifiers: public, < >, abstract, final, strictfp1

Page 3: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 3

Member Variables

Member variables declaration appears within the class body but

outside of any methods or constructors.

public static Vector cubeVertices;private final int id = 0;

321 4

5 initilizer

1 Access modifiers: public, protected, private, < >

2

static – variable is a class variable

Attribuesfinal – the value of the variable cannot be changed

transient – marker used in object serializationvolatile – prevent compiler from optimization

type name

Page 4: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 4

Constructors - super(); this(); class AnimationThread extends Thread { int framesPerSecond; int numImages; Image[] images;

AnimationThread(int fps) { super("AnimationThread"); super() superclass constructor

invocation framesPerSecond = fps; }

AnimationThread(int fps, int num) { this(fps); this() explicit constructor invocation numImages = num;

} AnimationThread(int fps, int num, Image[] images ) { super("AnimationThread"); framesPerSecond = fps; numImages = num; this.images = images; } this current object reference}

Page 5: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 5

Constructor’s Modifiers

One can specify how other objects can create instances of a given class by using an access modifier in the constructors' declaration:

private No other class can instantiate the given class. The class may contain public class methods (sometimes called factory methods), and those methods can construct an object and return it, but

no other classes can.

protected Only subclasses of the given class can create instances of it.

public Any class can create an instance of the given class.

no modifiers gives package access Only classes within the same package as the class can construct an instance of it.

Page 6: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 6

Method Declaration

The only required elements of a method declaration are the method’s name, its return type, and a pair of parentheses ( ).

public abstract int doIt(Object o) throws Exception

1 2 3

4 5

6Return type

Method name Parametes List

Checked exceptionsMethod Signature

1Access modifiers: public, protected, private, < >

2

static – method is a class methodabstract – method has no implementation – abstract classfinal – method cannot be overridden by a subclassnative – method implemented in a language other than Javasynchronized – method has a thread-safe implementation

Attribues

strictfp – strict constrain for floating point arithmetic

Page 7: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 7

Overloading

Defining more methods with the same name, but with different signature is called method overloading. Java supports method name overloading so that multiple methods

can share the same name.

Ex:

class ShapeRender {…void draw(Shape s) { …}void draw(Rectagle r) { …}void draw(Circle c, Point position) { …}…

}

Page 8: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 8

Inheritance

Definition: A subclass is a class that extends another class. A subclass inherits state and behavior from all its ancestor. The superclass refers to a direct ancestor.

Subclass inherits all superclasses members and can access any member declared as public or protected or declared with no access specifier as long as the subclass is in the same package as the superclasses.

public class SubClass extends SuperClass { … }

public class SuperClass { … }

Page 9: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 9

Overriding

Replacing the superclass’s implementation with a new method in a subclass is called overriding. The signature and the return type should be identical. Only accessible non-static method can be overridden. Access modifier could be different in overridden method as long as the

subclass modifier is less restrictive then the superclass. A subclass can change whether a parameter in an overriddent method is

final ( final is not part of method signature). Each type in overriding method’s throws clause must be

polymorphically compatible with a least one of the types listed in the throws clause of the supertype’s method.

Fields cannot be overridden; they can only be hidden.

super acts as a reference accessing fields and method of superclass.

• Ex: super.superclassField;

Page 10: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 10

Example of Overriding

class Base {public String str = “BaseString”;public void show() { System.out.println(“Base show() “ + str); }

}

class Extended extends Base {public String str = “ExtendedString”;public void show() { System.out.println(“Extended show() “ +

str); }public static void main(String[ ] args) {

Extended e = new Extended();Base b = e;b.show(); e.show();System.out.println(b.str + “ “ + e.str); } }

Results: 1. b.show() Extended show() ExtendedString

2. e.show() Extended show() ExtendedString3. b.str + e.str BaseString ExtendedString

When invoke a method on an object, the actual class of the object governs which implementation is used.When access a field the declared type of the referenced is used.

Page 11: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 11

Polymorphismclass Point { int x; int y; void clear() { x = 0; y = 0 } }

class Pixel extends Point {Color color;public void clear() { super.clear(); color = null;}

}Pixel extends both data and behavior of its Point superclass.All the Point code can be used by any one with a Pixel in hand.

A single object like Pixel could have many (poly) forms (-morph) and can be used as both a Pixel object and a Point object. Pixel’s behavior extends Point’s behavior.

Point point = new Pixel();Implicit casting – a reference of extended class is assigned to a reference of the base class – upcasting.

Point object

objectPixel

Page 12: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 12

Constructor Order

Each constructor has three phases: 1. Invoke a superclass’s constructor. 2. Initialize the fields using their initializers and any initialization block.

zero for all numeric types, false for boolean,\u0000 for char, null for references.

3. Execute the body of constructor.

Each class has a least one constructor If class has no constructor the compiler adds the default constructor.Ex:

class Bush { Bush(int i){ … } Bush(double d) { …} }

An invocation Bush bushObj = new Bush(); will generate a compile error – there is no default constructor.

Page 13: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 13

Abstract Class

A method that provides only the definition without an implementation is called abstract method.A class that defines only part of its methods is called and declared as an abstract class.

An abstract class could contain abstract mehtods and concret methodsEx:

abstract class Benchmark {public long repeat(int count) {

long start = System.currentTimeMillis();for (int k = 0; k < count; k++)

long now = System.currentTimeMillis();

benchmark();return now – start;

}}abstract void benchmark(); //definition without

implementation}

Page 14: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 14

Interface

A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface. Methods in an interface are implicitly abstract and public. Fields in an interface are always static and final. A class could implement more than one interface – multiple inheritance. Interface definition creates type name just as class definition do.Ex:

public interface X {int MAX_VAL_SIZE = 10;Object setObject();

}public class A extends B implements X {

Object setObject() { Object o; … return o; }

}

Page 15: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 15

Interface – a Type Name

Interface definitions create type names just as class definition do.An interface defines a protocol of behavior. A class that implements an interface adheres to the protocol defined by that interface.

Ex: public interface ConversionFactors {

double INCH_TO_MM = 25.4;}

public interface Conversions extends ConversionFactors {

double inchToMM(double inches); } public class Transform implements Conversions {

public double inchToMM(double inches) {return inches * INCH_TO_MM;

}}

Conversions conv = new Transform();

Page 16: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 16

Packages

Packages are collections of related classes, interfaces, and subpackages. Interfaces and class can use normal public names without any

conflict with similar common names. Packages can have types and members that are available only within

the package and are inaccessible to outside code.

package com.magic.attributes;Ex: Some of the packages in JDK 1.2

java.applet; java.awt; java.awt.*;java.beans; java.io; java.lang;java.rmi; java.security; java.util;java.naming; javax.swing;org.omg.CORBA;

Should be the first line in a prgramm

Page 17: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 17

Nested Class

Definition: A nested class is a class that is a member of another class.One use nested classes to reflect the relationship between two classes.

class EnclosingClass{ . . . class ANestedClass { . . . } }

A static nested class is called just that: a static nested class. A nonstatic nested class is called an inner class. class

public EnclosingClass { . . . public static class AStaticNestedClass { . . . } protected class InnerClass { . . . } }

Page 18: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 18

Inner Class

Definition: An inner class is a nested class whose instance exists within an instance of its enclosing class and has direct access to the instance members of its enclosing instance. public class Stack {

private Vector items; ...//code for Stack's methods and constructors not shown... public Enumeration enumerator() { return new StackEnum(); }

class StackEnum implements Enumeration { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); } } }

Instance of Enclosing Class

Stack

Instance of Inner Class

StackEnum

Page 19: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 19

Anonymous ClassesDefinition: An inner class without a name is called anonymous class.public class Stack { private Vector items; ...//code for Stack's methods not shown... public Enumeration enumerator() { return new Enumeration() { int currentItem = items.size() - 1; public boolean hasMoreElements() { return (currentItem >= 0); } public Object nextElement() { if (!hasMoreElements()) throw new NoSuchElementException(); else return items.elementAt(currentItem--); } } } }

Interface Enumeration

public boolean hasMoreElements();

public Object nextElement();

Page 20: Copyright @ 2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and

Copyright @ 2000 Jordan Anastasiade. All rights reserved. 20

Conclusions

After completion of this lesson you should know:How to write Java Program using Inheritance.

How to write Java Program using Polymorphism.

Creating and using Packages.