570 likes | 597 Views
Learn about creating classes, managing inheritance, nested classes, annotations, generics, constructors, passing information, access levels, instance, and class members in Java programming. Understand method declaration elements, instance and class members, overriding methods, and static initialization blocks with examples.
E N D
Java Programming: Classes and Inheritance Vyacheslav Grebenyuk CTDE, AI dept., KhNURE
Content • Creating Classes • Managing Inheritance • Nested Classes • Enumerated Types • Annotations • Generics (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Creating Classes (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Declaring Classes Class Declaration Elements (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Declaring Member Variables Variable Declaration Elements (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Defining Methods Method Declaration Elements (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Meanless • Providing Constructors for Your Classes • Passing Information into a Method or a Constructor • Returning a Value from a Method • Using the this Keyword (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Controlling Access to Members of a Class Access Levels (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Understanding Instance and Class Members import java.util.*; public class AClass { public int instanceInteger = 0; public int instanceMethod() { return instanceInteger; } public static int classInteger = 0; (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Understanding Instance and Class Members 2 public static int classMethod() { return classInteger; } public static void main(String[] args) { AClass anInstance = new AClass(); AClass anotherInstance = new AClass(); //Refer to instance members through an instance. anInstance.instanceInteger = 1; (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Understanding Instance and Class Members 3 anotherInstance.instanceInteger = 2; System.out.format("%s%n", anInstance.instanceMethod()); System.out.format("%s%n", anotherInstance.instanceMethod()); //Illegal to refer directly to instance members from a class method //System.out.format("%s%n", instanceMethod()); //illegal //System.out.format("%s%n", instanceInteger); //illegal //Refer to class members through the class... AClass.classInteger = 7; (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Understanding Instance and Class Members 4 System.out.format("%s%n", classMethod()); //...or through an instance. (Possible but not generally // recommended.) System.out.format("%s%n", anInstance.classMethod()); //Instances share class variables anInstance.classInteger = 9; System.out.format("%s%n", anInstance.classMethod()); System.out.format("%s%n", anotherInstance.classMethod()); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Program results • Here's the output from the program: 1 2 7 7 9 9 (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
public class BedAndBreakfast { //initialize to 10 public static final int MAX_CAPACITY = 10; //initialize to false private boolean full = false; } You can use the ?: cannot call any method that is declared to throw a checked exception methods that throws an unchecked (runtime) exception cannot do error recovery Initializing Instance and Class Members (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Using Static Initialization Blocks import java.util.*; class Errors { static ResourceBundle errorStrings; static { try { errorStrings = ResourceBundle.getBundle("ErrorStrings"); } catch (MissingResourceException e) { //error recovery code here } } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Managing Inheritance All Classes are Descendants of Object (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Overriding and Hiding Methods • A subclass cannot override methods that are declared final in the superclass • A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract • When overriding a method, you might want to use the @Override annotation (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Overriding and HidingMethods 2 public class Animal { public static void hide() { System.out.format("The hide method in Animal.%n"); } public void override() { System.out.format("The override method in Animal.%n"); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Overriding and HidingMethods 3 public class Cat extends Animal { public static void hide() { System.out.format("The hide method in Cat.%n"); } public void override() { System.out.format("The override method in Cat.%n"); } public static void main(String[] args) { Cat myCat = new Cat(); Animal myAnimal = myCat; //myAnimal.hide(); //BAD STYLE Animal.hide(); //Better! myAnimal.override(); } } The hide method in Animal. The override method in Cat. (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Overriding and HidingMethods 4 Defining a Method with the Same Signature as a Superclass's Method (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Hiding Member Variables • Within a class, a member variable that has the same name as a member variable in the superclass hides the superclass's member variable, even if their types are different • the member variable must be accessed through super (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Using super public class Superclass { public boolean aVariable; public void aMethod() { aVariable = true; } } public class Subclass extends Superclass { public boolean aVariable; //hides aVariable in Superclass //not recommended public void aMethod() { //overrides aMethod in Superclass aVariable = false; super.aMethod(); System.out.format("%b%n", aVariable); System.out.format("%b%n", super.aVariable); } } Results: false true (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Super keyword to invoke a superclass's constructor public final class TransactionFailedException extends Exception { static final long serialVersionUID = -8919761703789007912L; public TransactionFailedException(Throwable cause) { super("Transaction failed", cause); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Being a Descendent of Object • Object class provides several useful methods that may need to be overridden by a well-behaved subclass: • equals and hashCode • toString (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Being a Descendent of Object 2 • Object class provides the following handy methods: • getClass • notify, notifyAll, and wait (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The clone Method aCloneableObject.clone(); • Class of object must implements the Cloneable interface (CloneNotSupportedException) • The simplest way to make your class cloneable, then, is to add implements Cloneable to your class's declaration (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The clone Method 2 public class Stack implements Cloneable { private ArrayList<Object> items; ... //Code for Stack's methods and constructornot shown. protected Stack clone() { try { //Clone the stack. Stack s = (Stack)super.clone(); //Clone the list. s.items = (ArrayList)items.clone(); return s; //Return the clone. } catch (CloneNotSupportedException e) { //This shouldn't happen because Stack and //ArrayList implement Cloneable. throw new AssertionError(); } } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The equals and hashCode Methods public class Book { ... public boolean equals(Object obj) { if (obj instanceof Book) { if (((Book)obj).getISBN().equals(this.ISBN)) { return true; } else { return false; } } else { return false; } } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The equals and hashCode Methods 2 • You should always override the equals method if the identity operator is not appropriate for your class • If you override equals, override hashCode as well (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The toString Method • The Object's toString method returns a String representation of the object System.out.format("%s%n", firstBook.toString()); • 0201914670: The JFC Swing Tutorial: A Guide to Constructing GUIs, 2nd EditionAuthors: Kathy Walrath, Mary Campione, Alison Huml, Sharon Zakhour (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The getClass Method • The getClass method returns a runtime representation of the class of an object • This method returns a Class object (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The getClass Method void printClassName(Object obj) { //The getSimpleName method was introduced in J2SE 5.0. //Prior to that, you can use getName, which returns //the fully qualified name, rather than just the //class name. System.out.format("The object's class is %s.%n“, obj.getClass().getSimpleName()); } • Two ways to get the Class object for the String class: String.class Class.forName("java.lang.String") (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Writing Final Classes and Methods class ChessAlgorithm { enum ChessPlayer { WHITE, BLACK } ... final ChessPlayer getFirstPlayer() { return ChessPlayer.WHITE; } ... } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Writing Abstract Classes and Methods • Skipped (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Nested Classes class EnclosingClass { ... class ANestedClass { ... } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Static nested class and inner class class EnclosingClass { ... static class StaticNestedClass { ... } class InnerClass { ... } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Enumerated Types • An enumerated type is a type whose legal values consist of a fixed set of constants enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The enum declaration defines a class (called an enum type) • Printed values are informative • They are typesafe • They exist in their own namespace • The set of constants is not required to stay fixed for all time (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The enum declaration defines a class (called an enum type) 2 • You can switch on an enumeration constant • They have a static values method that returns an array containing all of the values of the enum type in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enumerated type (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
The enum declaration defines a class (called an enum type) 3 • You can provide methods and fields, implement interfaces, and more • They provide implementations of all the Object methods. They are Comparable and Serializable, and the serial form is designed to withstand changes in the enum type (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Planet public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7), PLUTO (1.27e+22, 1.137e6); private final double mass; //in kilograms private final double radius; //in meters (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Planet 2 Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } public double mass() { return mass; } public double radius() { return radius; } //universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; public double surfaceGravity() { return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Planet3 public static void main(String[] args) { double earthWeight = Double.parseDouble(args[0]); double mass = earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) { System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); } } Here's the output: $ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 Your weight on MARS is 66.279007 Your weight on JUPITER is 442.847567 Your weight on SATURN is 186.552719 Your weight on URANUS is 158.397260 Your weight on NEPTUNE is 199.207413 Your weight on PLUTO is 11.703031 (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Annotations • Release 5.0 of the JDK introduced a metadata facility called annotations • Annotations provide data about a program that is not part of the program, such as naming the author of a piece of code or instructing the compiler to suppress specific errors (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Annotations 2 @Author("MyName") class myClass() { } @SuppressWarnings("unchecked") void MyMethod() { } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Annotations 3 • @Deprecated • the marked method should no longer be used • The compiler generates a warning whenever a program uses a deprecated method, class, or variable • @Override • the element is meant to override an element declared in a superclass • @SuppressWarnings • tells the compiler to suppress specific warnings that it would otherwise generate (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Annotations example import java.util.List; class Food {} class Hay extends Food {} class Animal { Food getPreferredFood() { return null; } /** * @deprecated document why the method was deprecated */ @Deprecated static void deprecatedMethod() { } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Annotations example 2 class Horse extends Animal { Horse() { return; } @Override Hay getPreferredFood() { return new Hay(); } @SuppressWarnings({"unchecked", "deprecation"}) void useDeprecatedMethod() { Animal.deprecateMethod();//deprecation warning-suppressed } } (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
public class Library { private List resources = new ArrayList(); public void addMedia(Media x) { resources.add(x); } public Media retrieveLast() { int size = resources.size(); if (size > 0) { return resources.get(size - 1); } return null; } } public class Media { } public class Book extends Media { } public class Video extends Media { } public class Newspaper extends Media { } Generics (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006
Generics //A Library containing only Books Library myBooks = new Library(); ... Book lastBook = (Book)myBooks retrieveLast(); (С) ЦТДО, каф. Искусственного интеллекта, ХНУРЭ, 2006