Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.

Similar presentations


Presentation on theme: "Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions."— Presentation transcript:

1 Chap. 1 Classes, Types, and Objects

2 How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions go here… }

3 A simple example template for a class definition without these optional clauses is as follows: class Gnome { // instance variable definitions would go here … // method definitions would go here … }

4 Class Modifiers abstract: describes a class that has abstract methods.  Abstract methods are declared with the abstract keyword and are empty.  A class that has nothing but abstract methods and no instance variables is more properly called an interface.  An abstract class usually has a mixture of abstract methods and actual methods.

5 An Example of Abstract Class public abstract class EulerTour { protected BinaryTree tree; // Execution of the traversal. This abstract method must be specified in a concrete subclass public abstract Object execute(BinaryTree T); protected void init(BinaryTree T) { tree = T; } … }

6 An Example of Interface public interface Stack { // return the number of elements in the stack public int size(); // return whether the stack is empty public boolean isEmpty(); // Inspect the element at the top of the stack public Object top() throws EmptyStackException; // Insert an element at the top of the stack public void push (Object element); // Remove the top element from the stack public Object pop() throws EmptyStackException; }

7 final: describes a class that can have no subclass. public: describes a class that can be instantiated or extended by anything in the same package or by anything that imports the class.  All public classes are declared in their own separate file called.java.  There can only be one public class per file.  If the public class modifier is not used, the class in considered friendly. This means that it can be used and instantiated by all classes in the same package. This is the default class modifier.

8 Base Types booleanBoolean value: true or false char16-bit Unicode character byte8-bit signed two’s complement integer short16-bit signed two’s complement integer int32-bit signed two’s complement integer long64-bit signed two’s complement integer float32-bit floating-point number (IEEE 754- 1985) double64-bit floating-point number (IEEE 754- 1985)

9 Objects = new ([param, param,…]); myPoint = new Point(3,6);

10 Number Objects Base TypeClass NameCreation ExampleAccess Example byteByten = new Byte((byte)34);n.byteValue() shortShortn = new Short((short)100);n.shortValue() intIntegern = new Integer(1045);n.intValue() longLongn = new Long(10849L);n.longValue() floatFloatn = new Float(3.934F);n.floatValue() doubleDoublen = new Double(3.934);n.doubleValue()

11 String Objects String concatenation String s = “kilo” + “meters”;

12 Instance Variables Syntax: [ ] [= ]; class Gnome { // instance variables; protected String name; protected int age; protected Gnome gnome_buddy; private boolean magical; public double height = 2.6; // an initialization public static final int MAX_HEIGHT = 3; // a constant // Methods definitions would go here… }

13 Variable Modifiers public: anyone can access public instance variables. protected: only methods of the same package or of subclass can access. private: only methods of the same class (not methods of a subclass) can access. If none is used, the instance variable is friendly. It can be accessed by any class in the same package.

14 static: is used to declare that a variable is associated with the class, not with individual instances of that class. Static variables are used to store “global” information about a class. final: a final instance variable is one that must be assigned an initial value, and then can never be assigned a new value after that.

15 Methods Syntax: [ ] ([ ]) { // method body … } has the syntax: [, [, …] ]

16 Example: Public void renameGnome(String s) { name = s; // Reassign the name instance variable of this gnome. }

17 Method Modifiers public: anyone can call public methods. protected: only methods of the same package or of subclasses can call a protected method. private: only methods of the same class (not methods of a subclass) can call a private method. If none is used, the method is friendly. Friendly methods can only be called by objects of classes in the same package.

18 The above method modifiers can be followed by the following to further restrict a method: abstract: an abstract method has no code. It only appears within an abstract class.  example:  public abstract void setHeight (double newHeight);

19 final: this is a method that cannot be overridden by a subclass. static: this is a method that is associated with the class itself, and not with a particular instance of the class.  Static methods can also be used to change the state of static variables associated with a class (provided these variables are not declared to be final).

20 Return Types If the method returns a value, it is called a function. If the method returns a void, it is called a procedure. Example: public boolean isMagical( ) { return magical; }

21 Parameters All parameters in Java are passed by value. The method can change the copy but not the original. If we pass an object reference as a parameter to a method, the reference is copied as well.

22 Constructor Methods A constructor is used to initialized newly created objects. [constructor_modifiers] ([ ]) { // constructor body … } A constructor has no return value. An abstract, static, or final constructor is not allowed.

23 For example: public Fish (int w, String n) { weight = w; name = n; } Fish myFish = new Fish (7, “Wally”);

24 The Main Method public static void main(String[ ] args) { // main method body … } Invoke the program by typing: java Aquarium 45 Args[0] is 45.

25 Complete example of the Gnome class public class Gnome { // instance variables protected String name; protected int age; protected Gnome gnome_buddy; private boolean magical = false; public double height = 2.6; // in feet public static final int MAX_HEIGHT = 3; // maximum height

26 // Constructors: Gnome (String nm, int ag, Gnome bud, double hgt) { // fully parameterized name = nm; age = ag; gnome_buddy = bud; height = hgt; }

27 Gnome( ) { // Default constructor name = “Rumple”; age = 204; gnome_buddy = null; height = 2.1; }

28 // Methods public static void makeKing (Gnome h) { h.name = “King ” + h.getRealName( ); h.magical = true; // Only the Gnome class can reference this field. } pubic void makeMeKing( ) { name = “King “+ getRealName( ); magical = true; }

29 public boolean isMagical( ) {return magical;} public void setHeight (int newHeight) { height = newHeight; } public String getName ( ) {return “I won’t tell!”; } public String getRealName( ) { return name; } public void renameGnome (String s) { name = s; }

30 Expressions String Concatenation String rug = “carpet”; String dog = “spot”; String mess = rug + dog; String answer = mess + “ will cost me “ + 5 + “ dollars!”; Result: “carpetspot will cost me 5 dollars!”

31 Implicit Casting with String Objects String s = (String) 4.5; // wrong String t = “Value = “ + (String)13; // wrong String u = 22; // wrong String s = “ “ + 4.5; // correct, but poor style String t = “Value = “ + 13; // good String u = Integer.toString(22); // good

32 Arrays To find the size of an array:.length // count the number of times an integer x appears in an array a public static int countInteger (int [ ] a, int x) { int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] != x) continue; count ++; } return count; }

33 The syntax for declaring an array: [ ] [= {,, …, }]; The syntax for creating an array: new [ ] int [ ] a = new int [10]; float [ ] [ ] x = new float [8][10];

34 Simple Input and Output Simple Output Methods System.out.print(“Java values: “); System.out.print(3.1415); System.out.print(‘,’); System.out.print(15); System.out.println(“ (double, char, int).”); Result: Java values: 3.1415, 15 (double, char, int).

35 Simple Input Methods int read( ): read a single char. String readLine( ): read a line of text up to the next newline character. Example: java.io.BufferedReader stndin; // Standard input (buffered) String line; // A line of input text double sum, d = 0.0; int i = 0; stndin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

36 System.out.print(“Input a double: “); System.out.flush( ); // clears the input stream if ((line = stndin.readLine( )) != null) d = Double.valueOf(line).doubleValue( ); System.out.print(“Input an int: “); System.out.flush( ); if ((line = stndin.readLine( ))!= null) i = Integer.valueOf(line).intValue( ); sum = d + i; System.out.println(“Their sum is “ + sum + “.”);

37 Result: Input a double: 6.1078 Input an int: 209 Their sum is 215.1078.


Download ppt "Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions."

Similar presentations


Ads by Google