Jump Start Java B Ramamurthy Copyright 1998 CSE
Jump Start : Java B. Ramamurthy Copyright 1998 CSE Department 10/18/2021 BR 1
CS 1 (as in CSE 115) CS 1 Problem Solving -- Design -- Tools -- Techniques -- Software Eng. -- Class libraries 10/18/2021 OO Design Prog. Lang Algorithms -- Class -- Elements -- Sort -- Object -- Control -- Search -- Methods Structures -- Attributes -- Data -- Relationships Structures -- Encapsulation Programming Special Features -- Inheritance Environment -- Design -- Polymorphism using GUI -- OS : Solaris 2. 7 (unix-based) -- JDK 1. 1. 6 -- Application, Applets BR 2
Topics for Discussion z z z OO Design Principles Java Virtual Machine Java Application Structure Class and objects Methods and Variables Access/Visibility Modifiers Debugging Inheritance Abstract classes, interfaces and implementation JDK Event Model Applets and Appletviewer Summary 10/18/2021 BR 3
Object-Oriented Principles OOP Encapsulation (class) -- Information Hiding -- Interface and Implementations -- Standardization -- Access Control mechanisms (private /public etc. ) 10/18/2021 Inheritance -- Hierarchy -- Reusability -- Extensibility -- Expressive power -- Reflects many real-world problems BR Polymorphism -- Many forms of same function -- Abstract Methods -- Abstract Classes 4
Conventional Compiled Languages C++source Mac Compiler Mac Hardware C++source PC Compiler PC Hardware C++source 10/18/2021 Sun Compiler BR Sun Hardware 5
Java Virtual Machine Java compiler : javac Java source JVM Byte code Mac interpreter Compiler Mac Hardware JVM Java source Byte code PC Interpreter PC Hardware JVM Java source 10/18/2021 Byte code Sun Interpreter BR Sun Hardware 6
“Run-anywhere” Capability z. On any machine when you compile Java source code using javac byte code equivalent to the source is generated. z. Byte code is machine-independent. This enables the “run-anywhere” capability. z. You invoke java command which will feed the byte code to the machine-dependent interpreter. 10/18/2021 BR 7
Java Application Program Interface (Java API) Package of related classes : java. awt java. util Date class 10/18/2021 (JAVA API) Random Dictionary Java. io, java. beans, . . Etc. . BR package 8
Java API : A Simplistic View API packages classes methods and data declarations 10/18/2021 BR 9
Java API Classes z Unlike many other languages, you will referring to the classes in the API. z Where is the API? z Packages are in: /util/lang/jdk 1. 2/src/java z “cd” to any package of interest: awt, lang, io, graphics…. . z You will see the methods and data defined in the classes in the package. 10/18/2021 BR 10
Types of Programs z Java is fully object-oriented. z Every “function” has to be attached to a class. z You will mainly deal with three types of programs: yclass: methods and data (variables + constants) describing a collection (type) of object yapplication: class that has a main method: represents a our regular program yapplet: class that is meant for execution using a appletviewer/browser 10/18/2021 BR 11
Problem Solving Using Java OO Design and Progamming in Java Identify classes needed Reuse API classes 10/18/2021 Reuse your classes Write an application class Design new classes BR Write an applet class Create and use objects 12
What is an Object? z Object-oriented programming supports the view that programs are composed of objects that interact with one another. z How would you describe an object? z Using its characteristics (has a ----? ) and its behaviors (can do ----? ) z Object must have unique identity (name) : Basketball, Blue ball z Consider a ball: y Color and diameter are characteristics (Data Declarations) y throw, bounce, roll are behaviors (Methods) 10/18/2021 BR 13
Classes are Blueprints z A class defines the general nature of a collection of objects of the same type. z The process creating an object from a class is called instantiation. z Every object is an instance of a particular class. z There can be many instances of objects from the same class possible with different values for data. 10/18/2021 BR 14
Example objects Object References red. Rose class Rose blue. Rose 10/18/2021 class BR 15
Instantiation : Examples z class Ford. Car ---- defines a class name Ford. Car z Ford. Car windstar; ---- defines a Object reference wind. Star z windstar = new Ford. Car(); ---- instantiates a windstar Object z class House. Plan 1 { color…. z House. Plan 1 blue. House; z blue. House = new House. Plan 1(BLUE); z House. Plan 1 green. House = new House. Plan 1(GREEN); 10/18/2021 BR 16
Operator new and “dot” znew operator creates a object and returns a reference to that object. z. After an object has been instantiated, you can use dot operator to access its methods and data declarations (if you have access permissions). z. EX: red. Rose. bloom(); green. House. color 10/18/2021 BR 17
Elements of a Class class header modifiers, type, name methods body parameters variables, constants assignment 10/18/2021 data declarations (variables, constants) BR statements selection repetition others 18
Class Structure class variables constants methods 10/18/2021 BR 19
Defining Classes z Syntax: z class_name { z data-declarations z constructors z methods } z Constructors are special methods used for instantiating (or creating) objects from a class. z Data declarations are implemented using variable and constant declarations. 10/18/2021 BR 20
Naming Convention z Constants: All characters in uppercase, words in the identifier separated by underscore: EX: MAX_NUM z Variables, objects, methods: First word all lowercase, subsequent words start with uppercase. EX: next. Int, my. Pen, read. Int() z Classes: Start with an uppercase letter. EX: Tree, Car, System , Math 10/18/2021 BR 21
A complete example z. Problem Statement: You have been hired to assist in an secret encryption project. In this project each message (string) sent out is attached to a randomly generated secret code (integer) between 1 and 999. Design and develop an application program in Java to carry out this project. 10/18/2021 BR 22
Identify Objects z. There are two central objects: y. Message y. Secret code z. Is there any class predefined in JAVA API that can be associated with these objects? Yes , y“string” of java. lang and “Random” of java. util 10/18/2021 BR 23
The Random class z. Random class is defined in java. util package. znext. Int() method of Random class returns an integer between 0 and MAXINT of the system. 10/18/2021 BR 24
Design Class Random Class String An instance of string Input and fill up message. An instance of Random number generator Generate Random integer Attach (concatenate) Output combined message. For implementation see /projects/bina/java/secret. Msg. java 10/18/2021 BR 25
Debugging and Testing z Compile-time Errors : Usually typos or syntax errors z Run-time Errors : Occurs during execution. Example: divide by zero. z Logic Errors: Software will compile and execute with no problem, but will not produce expected results. (Solution: testing and correction) 10/18/2021 BR 26
Class Components z Class name (starts with uppercase), constants, instance variables, constructors definitions and method definitions. z Constants: public final static double PI = 3. 14; z Variables: private double bonus; public string name; 10/18/2021 BR 27
Method Invocation/Call z Syntax: method_name (values); object_name. method_name(values); classname. method_name(values); Examples: compute. Sum(); // call to method from within the class where it is located Your. Rose. paint. It(Red); Math. abs(X); 10/18/2021 BR 28
Defining Methods z. A method is group of (related) statements that carry out a specified function. z. A method is associated with a particular class and it specifies a behavior or functionality of the class. z. A method definition specifies the code to be executed when the method is invoked/activated/called. 10/18/2021 BR 29
Method Definition : Syntax visibility return_type method_name (parameter_list) { statements } 10/18/2021 BR 30
Return Type zcan be void, type or class identifier zvoid indicates that the method called to perform an action in a self-standing way: Example: println ztype or class specify the value returned using a return statement inside the method. 10/18/2021 BR 31
Return Statement z. Syntax of return statement: return; // for void methods return expression; // for type or class return value // the expression type and return type should be same 10/18/2021 BR 32
Parameter List z Parameter list specified in method header provides a mechanism for sending information to a method. z It is powerful mechanism for specializing an object. z The parameter list that appears in the header of a method yspecifies the type and name of each parameter and yis called formal parameter list. z The corresponding parameter list in the method invocation is called an actual parameter list. 10/18/2021 BR 33
Parameter list : Syntax z Formal parameter list: This is like molds or templates (parm_type parm_name, . . ) z Actual parameter list: This is like material that fit into the mold or template specified in the formal list: (expression, expression. . ) 10/18/2021 BR 34
Method Definition : review definition header body Visibility modifiers return type Name parameter list { statements } 10/18/2021 BR 35
Method Definition : Example z. Write a method that computes and returns the perimeter of a rectangle class. z. Analysis: y. Send to the method: Length and Width y. Compute inside the method: Perimeter y. Return from the method: Perimeter 10/18/2021 BR 36
. . . Example (contd. ) public int Perimeter (int Length, int Width) { int Temp; // local temporary variable Temp = 2 * (Length + Width); // compute perimeter return Temp; // return computed value } 10/18/2021 BR 37
What happens when a method is called? z. Control is transferred to the method called and execution continues inside the method. z. Control is transferred back to the caller when a return statement is executed inside the method. 10/18/2021 BR 38
Method Invocation : semantics Operating System 1 4 2 Main method 8 Rect. Area(…. ) 3 7 8 Area 5 method 6 10/18/2021 BR 1. OS to main method 2. Main method execution 3. Invoke Area 4. Transfer control to Area 5. Execute Area method 6. Return control back to main method 7. Resume executing main 8. Exit to OS 39
Constructors z. A Constructor is used to create or instantiate an object from the class. z. Constructor is a special method: y. It has the same name as the class. y. It has no return type or return statement. z. Typically a class has more than one constructor: a default constructor which has no parameters, and other constructors with parameters. 10/18/2021 BR 40
Constructors (contd. ) z You don’t have to define a constructor if you need only a default constructor. z When you want initializing constructors : 1. you must include a default constructor in this case. 2. You will use initializing constructors when you want the object to start with a specific initial state rather than as default state. 3. Example: Car my. Car(Red); // initializing constructor for Car class with color as parameter 10/18/2021 BR 41
Visibility Modifiers type Method/variable name public protected “nothing” DEFAULT private static To indicate class method/ variable 10/18/2021 BR “nothing” DEFAULT To indicate object method/ variable 42
. . Modifiers (contd. ) zprivate : available only within class z“nothing” specified : DEFAULT: within class and within package zprotected : within inherited hierarchy (only to sub classes) zpublic : available to any class. 10/18/2021 BR 43
CLASSPATH z. Many times classes needed are available in a repository other than the Java API. z. Set the CLASSPATH environment variable to point to such repositories. One such is located in /projects/bina/cs 116/ z setenv CLASSPATH. : /util/lang/jdk 1. 1. 6/lib/classes. zip: /projects/bina/cs 116/ z You may import packages from this directory or use classes from this directory. 10/18/2021 BR 44
Applet z. An applet is a Java program that operates within a browser and hence can appear in a web page. z. It can be fetched from a remote computer and run on the local computer. z. Applet’s enabling technologies: y. Java Virtual Machine (JVM) y. Interpretation rather than compilation 10/18/2021 BR 45
Requirements z Besides the classes, an applet requires a. html file and a tool for viewing the applet (Ex: appletviewer of JDK) z An applet extends Applet class of java. applet package. import java. applet. Applet; z An applet should have at least an init() or a paint() method (just as an application should have main() method) 10/18/2021 BR 46
Applet Class z. Applet class has four important methods: init() start() stop() destroy() Besides these paint() method of component class is commonly used for drawing graphics in an applet window. 10/18/2021 BR 47
Applet Runtime Structure Applet file. javac html file includes. html appletviewer Applet file. class 10/18/2021 BR Java runtime JVM 48
Example 1: Using only paint() z //file : My. Applet. java import java. applet. Applet; // step 1 import java. awt. Graphics; public class My. Applet extends Applet //step 2 { public void paint( Graphics g) // step 3 { g. draw. String(“To climb a ladder”, 20, 90); } } 10/18/2021 BR 49
Example 1: interpretation step 1: import Applet class step 2: inherit from Applet class step 3: Overload /redefine/customize paint() method 10/18/2021 BR 50
html file 1. Create a html file: <APPLET code=“My. Applet. class” width=300 height=200> <APPLET> 2. Save as My. Applet. html 3. To create class: javac My. Applet. java 4. To execute: appletviewer My. Applet. html 10/18/2021 BR 51
Example 1: execution semantics Java run-time system will look for init(), then start() methods. Default definitions of init() and start() are executed. Then user-applet-defined paint() method is executed. Rest of the control follows default methods. 10/18/2021 BR 52
More on Applets 1. main() is replaced by init() or paint() methods 2. An applet cannot access local programs or files 3. Very useful in creation of active/dynamic web pages 4. Implements “behavior streaming” 5. Popular component of Java language. 10/18/2021 BR 53
On-line Information file: /util/lang/jdk 1. 2/docs/index. html has user’s manual for Java API It is extensive documentation with references to books, and other material of interest. 10/18/2021 BR 54
- Slides: 54