EEC 484 Computer Networks Java Tutorial #1 Wenbing Zhao

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming in Java. Characteristics of Object Oriented Programming  Object Programming classes  Encapsulation  Polymorphism  Inheritance.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance Inheritance Reserved word protected Reserved word super
OBJECT-ORIENTED PROGRAMMING CONCEPTS (Review). What is an Object? What is an Object? Objects have states and behaviors. Example: A dog has states - color,
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
EEC-681/781 Distributed Computing Systems Java Tutorial Wenbing Zhao Cleveland State University
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Java Programming Chapter 3 More about classes. Why?  To make classes easier to find and to use  to avoid naming conflicts  to control access  programmers.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
Unit 051 Packages What is a Package? Why use Packages? Creating a Package Naming a Package Using Package Members Managing Source and Class Files Visibility.
Object Oriented Paradigm Programming Paradigms En Mohd Norafizal A.Aziz.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Chapter 4 Objects and Classes.
Packages F Package is a container for classes F A package is a grouping of related types (classes and interfaces) providing access protection and name.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Inheritance in the Java programming language J. W. Rider.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Object Oriented Programming Concepts. Object ► An object is a software bundle of related state and behavior. ► Software objects are often used to model.
By Waqas The topmost class in the java class hierarchy is called “Object”. If you declare a class which does not sub class of any super class.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
JAVA Programming (Session 4) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
Classes, Interfaces and Packages
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
What Is a Package? A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar.
By : Robert Apeldorn. What is OOP?  Object-oriented programming is a programming paradigm that uses “objects” to design applications and computer programs.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
1 COMP9024: Data Structures and Algorithms Week One: Java Programming Language (II) Hui Wu Session 2, 2014
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Introduction to Object-oriented Programming
Modern Programming Tools And Techniques-I
COMP9024: Data Structures and Algorithms
Software Construction
University of Central Florida COP 3330 Object Oriented Programming
COMP9024: Data Structures and Algorithms
Final and Abstract Classes
Inheritance and Polymorphism
Introduction to Exceptions in Java
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
03/10/14 Chapter 9 Inheritance.
Chapter 3 Inheritance © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
البرمجة الكينونية بلغة جافا 1294
Interface.
Java Programming Language
Packages and Interfaces
Week 6 Object-Oriented Programming (2): Polymorphism
Package & Java Access Specifiers
Interfaces.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Inheritance Inheritance is a fundamental Object Oriented concept
Selenium WebDriver Web Test Tool Training
Final and Abstract Classes
CMSC 202 Exceptions.
Presentation transcript:

EEC 484 Computer Networks Java Tutorial #1 Wenbing Zhao Cleveland State University wenbing@ieee.org

Outline Dissect a simple Java program Object-oriented programming concepts Exceptions handling Packages Materials taken from Sun’s Java Tutorial: http://download.oracle.com/javase/tutorial/java/index.html Another good Java tutorial: http://www.cafeaulait.org/course/ 9/15/2018 EEC484 Computer Networks

public class Calculator { private int m_num1; / / first number private int m_num2; // second number private char m_op; // operator: add, sub, mul, div private int m_result; // result of the calculation public Calculator() { m_num1 = 0; m_num2 = 0; m_op = ' '; m_result = 0; } public void enter1stNumber(int num1) { m_num1 = num1; public void enter2ndNumber(int num2) { m_num2 = num2; public void enterOperator(char op) { m_op = op; 9/15/2018 EEC484 Computer Networks

/* return the result of the calculation */ public int calculate() { switch(m_op) { case '+': return m_num1 + m_num2; case ' - ': return m_num1 m_num2; case '*': return m_num1 * m_num2; case '/': return m_num1 / m_num2; default: return 0; } 9/15/2018 EEC484 Computer Networks

ic void main(String[] args) { Calculator c = new Calculator(); public stat ic void main(String[] args) { Calculator c = new Calculator(); c.enter1stNumber(1); c.enterOperator('+'); c.enter2ndNumber(1); int result = c.calculate(); System.out.println("1+1="+result); } 9/15/2018 EEC484 Computer Networks

How to learn a programming language quick and dirty? Search for APIs and examples on the Web! Tasks: get input from standard input (stdin) Make sure it is not empty For number input, make sure it is an integer For operator input, make sure it is a valid operator Deal with exceptions 9/15/2018 EEC484 Computer Networks

Object Concept Real-world objects: state and behavior State of a bicycle: current gear, current pedal cadence, current speed Behavior of a bicycle: changing gear, changing pedal cadence, applying brakes 9/15/2018 EEC484 Computer Networks

Software Object A software object mimics a real-world object Fields (state) A software object mimics a real-world object Member variables (or fields): store the state of the object Member functions (or Methods): expose the object behavior Methods operate on an object's internal state Methods (behavior) 9/15/2018 EEC484 Computer Networks

Object Oriented Concept Object-oriented communication: Different objects communicate (interact) with each other by calling methods defined in the objects Data encapsulation: Hiding internal state and requiring all interaction to be performed through an object's methods 9/15/2018 EEC484 Computer Networks

Class A class is the blueprint from which individual objects are created public class Bicycle { private int speed = 0; int gear = 1; public Bicycle() { gear = 1; speed = 0; } void changeGear(int newValue) { gear = newValue; void spe edUp(int increment) { speed = speed + increment; void applyBrakes(int decrement) { speed = speed - decrement; 9/15/2018 EEC484 Computer Networks

Access Level Modifiers At the top level—public, or package-private (no explicit modifier) At the member level—public, private, protected, or package-private (no explicit modifier) Access Levels Modifier Class Package Subclass World public Y protected N no modifier private 9/15/2018 EEC484 Computer Networks

Creating Objects Bicycle b = new Bicycle() Declaration: associate a variable name with an object type Instantiation: The new keyword is a Java operator that creates the object Initialization: The new operator is followed by a call to a constructor, which initializes the new object 9/15/2018 EEC484 Computer Networks

Using Objects Calling an object’s methods: Referencing an object’s fields: Bicycle b = new Bicycle() b.speedup(10); Calling an object’s methods: append the method's name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses. objectReference.fieldName 9/15/2018 EEC484 Computer Networks

Returning a Value from a Method A method returns to the code that invoked it when it completes all the statements in the method, reaches a return statement, or throws an exception (covered later), whichever occurs first return returnValue; return; If no return value is needed 9/15/2018 EEC484 Computer Networks

Inheritance Different kinds of objects often have a certain amount in common with each other Mountain bikes, road bikes, all share the characteristics of bicycles (current speed, current pedal cadence, current gear) Yet each also defines additional features that make them different Road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio 9/15/2018 EEC484 Computer Networks

Inheritance Classes can inherit commonly used state and behavior from other classes Bicycle is the superclass of MountainBike, RoadBike, and TandemBike In the Java, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses class MountainBike extends Bicycle { // new fields and methods defining a moun tain bike would go here } 9/15/2018 EEC484 Computer Networks

Inheritance Super class Subclasses 9/15/2018 EEC484 Computer Networks

Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class, or child class) The class from which the subclass is derived is called a superclass (also a base class or a parent class) A subclass inherits all the members (fields, methods, and nested classes) from its superclass Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass 9/15/2018 EEC484 Computer Networks

Inheritance MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it public class MountainBike extends Bicycle { // the MountainBike subclass adds one field publi c int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int startHeight) { super(); seatHeight = startHeight; } // the MountainBike subclass adds one method public void setHeight(int newVal ue) { seatHeight = newValue; 9/15/2018 EEC484 Computer Networks

Inheritance You can assign a subclass to a superclass variable Bicycle b = new MountainBike(10); But not the other way around. You have to cast a superclass object to a sublass object MountainBike mb = (MountainBike)b; 9/15/2018 EEC484 Computer Networks

Abstract Class An abstract class is a class that is declared abstract: it may or may not include abstract methods public abstract class GraphicObject { // declare fields // declare non - abstract methods abstract void draw(); } 9/15/2018 EEC484 Computer Networks

Abstract Class An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon If a class includes abstract methods, the class itself must be declared abstract Abstract classes cannot be instantiated, but they can be subclassed 9/15/2018 EEC484 Computer Networks

Abstract Class: Example abstract class GraphicObject { int x, y; ... void moveTo(int newX, int newY ) { } abstract void draw(); abstract void resize(); class Circle extends GraphicObject { void draw() { ... } void resize() { class Rectangle extends GraphicObject { 9/15/2018 EEC484 Computer Networks

Interface interface Bicycle { void changeCadence(int newValue); Objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with outside world An interface is a group of related methods with empty bodies interface Bicycle { void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); } 9/15/2018 EEC484 Computer Networks

Interface To implement this interface, use the implements keyword in the class declaration: class ACMEBicycle implements Bicycle { // remainder of t his class implemented as before } 9/15/2018 EEC484 Computer Networks

Interface Interfaces form a contract between the class and the outside world This contract is enforced at build time by the compiler If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile Implementing an interface allows a class to become more formal about the behavior it promises to provide 9/15/2018 EEC484 Computer Networks

Exception An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions 9/15/2018 EEC484 Computer Networks

Exception Code that might throw certain exceptions must be enclosed by either of the following: A try statement that catches the exception. The try must provide a handler for the exception A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception public void writeList() throws IOException { … } 9/15/2018 EEC484 Computer Networks

Exception Try-Catch-Finally try { } catch (FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); throw new SampleException(e); } catch (IOException e) { System.err.println("Caught IOException: " } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } 9/15/2018 EEC484 Computer Networks

How to Throw an Exception All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object public Object pop() { Object obj; if (size == 0) { throw new EmptyStackException(); } obj = objectAt(size - 1); setObjectAt(size 1, null); size -- ; return obj; 9/15/2018 EEC484 Computer Networks

Throwable Class and Its Subclasses 9/15/2018 EEC484 Computer Networks

Package A package is a namespace that organizes a set of related classes and interfaces Think of packages as being similar to different folders The Java platform provides an enormous class library (a set of packages) This library is known as the "Application Programming Interface", or "API" for short Java platform API specification: http://java.sun.com/reference/api/ Example packages: java.lang (Fundamental classes), java.io (Classes for reading and writing) 9/15/2018 EEC484 Computer Networks

Benefits of Creating a Package You and other programmers can easily determine that these types are related You and other programmers know where to find types that can provide graphics-related functions The names of your types won't conflict with the type names in other packages because the package creates a new namespace You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package 9/15/2018 EEC484 Computer Networks

Creating a Package To create a package, you choose a name for the package and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package The package statement (for example, package graphics;) must be the first line in the source file There can be only one package statement in each source file 9/15/2018 EEC484 Computer Networks

in the Draggable.java file package graphics; // in the Draggable.java file package graphics; public interface Draggable { . . . } in the Graphic.java file public abstract class Graphic { in the Circle.java file public class Circle extends Gra phic implements Draggable { in the Rectangle.java file public class Rectangle extends Graphic implements Draggable { 9/15/2018 EEC484 Computer Networks

Managing Source and Class Files Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example: // in the Rectangle.java file package graphics; public class Rectangle() { . . . } 9/15/2018 EEC484 Computer Networks

Managing Source and Class Files Then, put the source file in a directory whose name reflects the name of the package: .....\graphics\Rectangle.java The qualified name of the package member and the path name to the file are parallel class name graphics.Rectangle pathname to file graphics/Rectangle.java Produce a jar file for your classes Under the parent directory of graphics jar –cf graphics.jar graphics 9/15/2018 EEC484 Computer Networks

Using a Package To use a public package member from outside its package, you must do one of the following: Refer to the member by its fully qualified name: System.out.println(“Hello World”); Import the package member import graphics.Rectange; Rectangle r = new Rectangle(); Import the member's entire package import graphics.*; Circle c = new Circle(); 9/15/2018 EEC484 Computer Networks

Accessing a Package (Compilation and Execution) For compilation: javac –classpath graphics.jar YourClass.java For execution: java –classpath graphics.jar YourClass 9/15/2018 EEC484 Computer Networks

Questions Real-world objects contain ___ and ___. A software object's state is stored in ___. A software object's behavior is exposed through ___. Hiding internal data from the outside world, and accessing it only through publicly-exposed methods is known as data ___. A blueprint for a software object is called a ___. 9/15/2018 EEC484 Computer Networks

Questions Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword. A collection of methods with no implementation is called an ___. A namespace that organizes classes and interfaces by functionality is called a ___. The term API stands for ___? 9/15/2018 EEC484 Computer Networks

Questions What is wrong with the following interface? Is the following interface valid? public interface SomethingIsWrong { void aMethod(int aValue){ System.out.println("Hi Mom"); } public interface Marker { } 9/15/2018 EEC484 Computer Networks

Questions Is the following code legal? try { } finally { } 9/15/2018 EEC484 Computer Networks