Interfaces and Packages

Slides:



Advertisements
Similar presentations
Yoshi
Advertisements

Lecture 15.1 Static Methods and Variables. © 2006 Pearson Addison-Wesley. All rights reserved Static Methods In Java it is possible to declare.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
PACKAGES. PACKAGES IN JAVA A package is a collection of related classes and interfaces in Java Packages help in logical grouping of classes and interfaces.
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.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
1 Lecture 2 Java Packages  What are Java packages?  Why do wee need packages?  How to create a Java package?  Some examples.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Handling Errors with Exception (in Java) Project 10 CSC 420.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
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.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
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.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
1 Features of Java (2) CS 3331 Sections 4.5 and 4.6.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
2 Interfaces and Packages 3 What is an Interface? An interface defines a protocol of behavior that can be implemented by any class anywhere in the class.
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.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Exception Handling and Event Handling
Chapter 10 – Exception Handling
Inheritance-Basics.
Inheritance and Polymorphism
Java Programming Language
Packages When we name a program , we name it by class name…
Exceptions, Interfaces & Generics
Introduction Exception handling Exception Handles errors
Creating and Modifying Text part 2
Interfaces.
Advanced Programming Behnam Hatami Fall 2017.
Interfaces and Packages
Interface.
Java Programming Language
Packages and 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 ,
Web Design & Development Lecture 7
Exception Handling in Java
Inheritance Inheritance is a fundamental Object Oriented concept
Applying OO Concepts Using Java
Lecture 11 Objectives Learn what an exception is.
Constructors, GUI’s(Using Swing) and ActionListner
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Exception Handling and Event Handling
Interfaces,Packages and Threads
CMSC 202 Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Interfaces and Packages

What is an Interface? An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. An interface is a named collection of method definitions (without implementations). Interface reserve behaviors for classes that implement them.

Methods declared in an interface are always public and abstract, therefore Java compiler will not complain if you omit both keywords Static methods cannot be declared in the interfaces – these methods are never abstract and do not express behavior of objects Variables can be declared in the interfaces. They can only be declared as static and final. – Both keyword are assumed by default and can be safely omitted. Sometimes interfaces declare only constants – be used to effectively import sets of related constants.

Interface vs. Abstract Class An interface is simply a list of unimplemented, and therefore abstract, methods. An interface cannot implement any methods, whereas an abstract class can. A class can implement many interfaces but can have only one superclass. An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

Defining an Interface Defining an interface is similar to creating a new class. An interface definition has two components: the interface declaration and the interface body. interfaceDeclaration { interfaceBody } The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface

public interface A { Public int a=6; Float b=3.45; Public void set(); Public void get(); } If you do not specify that your interface is public, your interface will be accessible only to classes that are defined in the same package as the interface

Implementing an Interface Include an implements clause in the class declaration. A class can implement more than one interface (the Java platform supports multiple inheritance for interfaces), so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. When implement an interface, either the class must implement all the methods declared in the interface and its superinterfaces, or the class must be declared abstract

Interface A { Public void set(); Public void get(); } Class B implements A Public void set() System.out.println(“implemented set”); Public void get() System.out.println(“implemented get”); Public void check() System.out.println(“normal method of class B”); }} Class Demo1 Public static void main(String ar[]) B b1=new B(); b1.set(); b1.get(); b1.check();

Multiple Inheritance Person Student Employee TeachingAssistant Multiple inheritance of class is not allowed in Java

Interface A { Public void set(); } Interface B Public void get(); } Class C implements A,B Public void set() System.out.println(“implement set from A”); } Public void get() System.out.println(“implement get from B”); } Public void put() System.out.println(“concrete method of C”); }} Class Demo2 Public static void main(String ar[]) C c1=new C(); c1.set(); c1.get(); c1.put(); }

What is Package? A package is a collection of related classes and interfaces providing access protection and namespace management. To make classes easier to find and to use To avoid naming conflicts To control access

Why Using Packages? Programmers can easily determine that these classes and interfaces are related. Programmers know where to find classes and interfaces that provide graphics-related functions. The names of classes won’t conflict with class names in other packages, because the package creates a new namespace. Allow classes within the package to have unrestricted access to one another yet still restrict access for classes outside the package

Put Your Classes and Interfaces into Packages It is no need to “create” packages, they come to existence as soon as they are declared The first line of your source file: package <package_name>; e.g. package cars; class Car { … } Every class must belong to one package. Only one package statement is allowed per source file. If package statement is omitted, the class belongs to a special default package – the only package in Java that has no name.

Partial Package Tree of Java lang String Math reflect Constructor Method awt Frame Button io ObjectInputStream ObjectOutputStream util Vector Random

Packages and Class Package names should be made as unique as possible to prevent name clashes Class name must be fully qualified with their package name. Except: Class name immediately following the class keyword, e.g. class Car{…} Class belongs to the same package as the class being currently defined Class is explicitly specified in one of the import statements Class belongs to java.lang package (all java.lang classes are implicitly imported)

import Statement To avoid typing fully qualified names – use import statements sandwiched between the package statement and class definition. e.g. package grand.prix; import java.lang.*; //implicitly specified import java.util.Random; import machines.vehicles.cars.*; import machines.*.*; //COMPILER ERROR! import Racer; //from default package class SuperFastCar extends FastCar { private Racer r; public static void main(String{[] args) Random RNG = new Random(); java.util.Vector v = new java.util.Vector(); }

Classpath Compiled classes can be stored in different locations in the file systems. How to locating these files – Setting a classpath which is a list of directories where class files should be searched e.g. If Java system is to find classes from the machines.vehicles.cars package , its classpath must point to C:\A\B\classes, the root of the package directory hierarchy.

Setup Classpath In command line c:\> java –classpath C:\A\B\classes machines.vehicles.cars.Car To avoid specify the classpath in every command, set classpath as a command shell environment variable: Windows: >set CLASSPATH = C:\A\B\classes >set CLASSPATH = .; %CLASSPATH% >echo %CLASSPATH% .; C:\A\B\classes Unix: $CLASSPATH = $HOME/A/B/classes $CLASSPATH = .: $CLASSPATH $echo $CLASSPATH .: home/santa/A/B/classes

Exception and Error Handling

What's an Exception? exception is shorthand for the phrase "exceptional event." An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Many kinds of errors can cause exceptions Hardware errors, like a hard disk crash, Programming errors, such as trying to access an out-of-bounds array element.

Process in Java When Errors Happen When an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is responsible for finding some code to handle the error. Creating an exception object and handing it to the runtime system is called throwing an exception.

Why Using Exceptions? Java programs have the following advantages over traditional error management techniques: Separate error handling code from “regular” code. Propagate errors up the call stack Group error types and error differentiation

Java exceptions must be instances of Throwable or any Throwable descendant. You can create subclasses of the Throwable class and subclasses of your subclasses. Each "leaf" class (a class with no subclasses) represents a specific type of exception and each "node" class (a class with one or more subclasses) represents a group of related exceptions

import java.io.*; public class InputFileDeclared { private FileReader in; public InputFileDeclared(String filename) throws FileNotFoundException in = new FileReader(filename); } public String getWord() throws IOException { int c; StringBuffer buf = new StringBuffer(); do c = in.read(); if (Character.isWhitespace((char)c)) return buf.toString(); else buf.append((char)c); } while (c != -1);

The try Block The first step in writing any exception handler is putting the Java statements within which an exception can occur into a try block. The try block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequent catch blocks) associated with it. Syntax: try { //java statements }

The catch Block(s) (1) Associate exception handlers with a try block by providing one or more catch blocks directly after the try block The catch block contains a series of legal Java statements. These statements are executed if and when the exception handler is invoked. Syntax: catch (AThrowableObjectType variableName) { //Java statements }

Program Using in-built exceptions Class Demo3 { Public Static void main(String ar[]) int c,b[10]; int a=Integer.parseInt(ar[0]); try If(a%2==0) c=10/0; } else{ b[15]=34;

Catch(ArithmeticException e1) { System. out Catch(ArithmeticException e1) { System.out.println(“Exception is:”+e1); } Catch(ArirayIndexOutOfBoundsException e2) System.out.println(“Exception is:”+e2); System.out.println(“out of all try catch blocks”);

Creating own Exception class class CustomExceptionDemo { Public Static void main(String ar[]) int n=Integer.parseInt(ar[0]); System.out.println(“main Starts”); Try if(n<0) Throw new CustomException(“number is negative”); }} Catch(CustomException ce1) System.out.println(“custom exception occurs”); }

Public class CustomException extends Exception { Public CustomException(String m) super(m); }

Java applet Vs java applications Do not need any external installation or wizards , gets transferred on to the local machine and may run as part of web browser through internet. Execution Starts with inti() method. Does work without main() method. Must run within a GUI (using AWT or Swing components). Required high security, as they are untrusted. Application:- Stand Alone, doesn’t need web Browser. Main() method required to start the Execution. Doesn’t work if main() method isn’t there. May or may not be a GUI. Does not require any security, as they are installed on the same machine.

Draw an applet import java.awt.*; import java.applet.*; public class Smileyface extends Applet { Public void paint(Graphics g) g.drawOval(60, 60, 200, 200); g.fillOval(90, 120, 50, 20); g.fillOval(190, 120, 50, 20); g.drawLine(165, 125, 165, 175); g.drawArc(110, 130, 95, 95, 0, -180); }