Java Review. Object Orientation
|
|
- Godwin Davis
- 6 years ago
- Views:
Transcription
1 CMSC433, Fall 2009 Programming Language Technology and Paradigms Java Review Adam Porter Object Orientation Combining data and behavior objects, not developers, decide how to carry out operations Sharing via abstraction and inheritance similar operations and structures are implemented once Emphasis on object-structure rather than procedure structure behavior more stable than implementation but procedure structure still useful 3 1
2 public class Complex { private double r, i; Example public Complex(double r, double i) { this.r = r; this.i = i; public String tostring() { return ( + r +, + i + ) ; public Complex plus(complex that) { return new Complex(r + that.r, i + that.i); 4 Using Complex public static void main(string[] args) { Complex a = new Complex(5.5,9.2); Complex b = new Complex(2.3,-5.1); Complex c; c = a.plus(b); System.out.println( a = + a); System.out.println( b = + b); System.out.println( c = + c); 5 2
3 The Class Hierarchy Classes by themselves are a powerful tool Support abstraction and encapsulation Java also provides two other abilities Interfaces allow type reuse Inheritance allows code reuse Note: When you inherit from a class, you also implement the class s interface 6 Project 1: Interfaces public interface Servlet { public void doget(string path, String options, OutputStream out) throws ServletException, ShutdownException; class HelloWorld implements Servlet {... Servlet s = ServletFactory.getInstance().getServlet( HelloWorld ); s.doget(...); 7 3
4 Interfaces An interface lists supported (public) methods No constructors or implementations allowed Can have final static variables A class can implement (be a subtype of) zero or more interfaces Given some interface I, declaring I x =... means x must refer to an instance of a class that implements I, or else null 8 Interface Inheritance Interfaces can extend other interfaces Sometimes convenient form of reuse Given interfaces I1 and I2 where I2 extends I1 If C implements I2, then C implements I1 Since a class can implement multiple interfaces, interface extensions are often not needed 9 4
5 Inheritance Each Java class extends or inherits code from exactly one superclass Permits reusing classes to define new objects Can define the behavior of the new object in terms of the old one 10 Example class Point { int getx() {... int gety() {... class ColorPoint extends Point { int getcolor() {... ColorPoint reuses getx() and gety() from Point ColorPoint implements the Point interface They can be used anywhere a Point can be 11 5
6 Subtyping Both inheritance and interfaces allow one class to be used where another is specified This is really the same idea: subtyping We say that A is a subtype of B if A extends B or a subtype of B, or A implements B or a subtype of B 12 Java Design Everything inherits from Object* Even arrays Allows sharing, generics, and more Object Number Thread Integer * Well, almost: there are primitive int, long, float, etc. 13 6
7 No Multiple Inheritance A class type can implement many interfaces But can only extend one superclass Not a big deal There are ways to get around it And it s complicated to implement well Never-ending debate on this point 14 Abstract Classes Sometimes want a class with some code, but with some methods unwritten It can t be an interface because it has code It can t be a regular class because it doesn t have all the code You can t instantiate such a class Instead, we can mark such a class as abstract And mark the unimplemented methods as abstract 15 7
8 Example from JDK public abstract class OutputStream { public abstract void write(int b)...; public void write(byte b[], int off, int len)... {... write(b[off + i]); Subclasses of OutputStream need not override the second version of write(...) But they do need to override the first one, since it s abstract (Note: They may want to override anyhow for efficiency) 16 I/O streams Raw communication takes place using streams InStream OutStream Process Java also provides readers and writers character streams Applies to files, network connections, strings, etc. 17 8
9 I/O Classes OutputStream byte stream going out Writer character stream going out InputStream byte stream coming in Reader character stream coming in 18 Some OutputStreams and Writers Example classes ByteArrayOutputStream goes to byte [] FileOutputStream goes to file OutputStreamWriter wraps around OutputStream to get a Writer takes characters, converts to bytes can specify encoding used to convert Other wrappers PrintWriter supports print, println StringWriter 19 9
10 Applications and I/O Java external interface is a public method public static void main(string [] args) args[0] is first argument unlike C/C++ System.out and System.err are PrintStreams should be PrintWriter, but would break 1.0 code System.out.print( ) prints a string System.out.println( ) prints a string with a newline System.in is an InputStream not quite so easy to use 20 Java Networking class Socket Communication channel class ServerSocket Server-side listen socket Awaits and responds to connection requests 21 10
11 Example Client/Server ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Server code server client Socket conn = new Socket ( ); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Client code 22 Example Client/Server ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Server code server client Socket conn = new Socket ( ); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Client code 23 11
12 Example Client/Server ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Server code server? client Socket conn = new Socket ( ); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Client code 24 Example Client/Server ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Server code server client Note: The server can still accept other connection requests on port 5001 Socket conn = new Socket ( ); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Client code 25 12
13 Example Client/Server ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Server code in server out client Socket conn = new Socket ( ); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Client code 26 Example Client/Server ServerSocket s = new ServerSocket(5001); Socket conn = s.accept(); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Server code in server out in out client Socket conn = new Socket ( ); InputStream in = conn.getinputstream(); OutputStream out = conn.getoutputstream(); Client code 27 13
14 Possible Failures Server-side ServerSocket port already in use Client dies on accept Client-side Server dead No one listening on port In all cases IOException thrown Must use appropriate throw/try/catch constructs 28 Demo Run a basic echo server 30 14
15 Objects and Variables Variables of a primitive type contain values e.g., byte, char, int,... int i = 6; Uninitialized values contain 0 Assignment copies values Variables of other types contain references to the heap int[] a = new int[3]; Objects are allocated with new Uninitialized object references are null Assignment copies references, not the objects themselves 31 Example int i = 6; int j; // uninitialized int [] a = {1, 3, 5, 7, 9; int [] b = new int[3]; String s = abcdef ; String t = null; 32 15
16 Example: Assignments j = i; b = a; t = s; 33 Garbage Collection What happens to array [0, 0, 0] in previous example? It is no longer accessible When Java performs garbage collection (GC) it will automatically reclaim the memory it uses Notice: No free() or delete in Java Makes it much easier to write correct programs Most of the time, very efficient 34 16
17 Mutability An object is mutable if its state can change Example: Arrays are mutable An object is immutable if its state never changes Once its been initialized Example: Strings in Java are not mutable There are no methods to change the state of a string 35 Example: Mutability a[1] = 0; // also changes b[1] Moral: Always be careful when you have aliasing Multiple references to the same object 36 17
18 Method Invocation Syntax o.m(arg1, arg2,..., argn); Run the m method of object o with arguments arg1...argn Two ways to reuse method names: Methods can be overridden Methods can be overloaded 37 Overriding Define a method also defined by a superclass class Parent { int cost; void add(int x) { cost += x; class Child extends Parent { void add(int x) { if (x > 0) cost += x; 38 18
19 Overriding (cont d) Method with same name and argument types in child class overrides method in parent class Arguments and result types must be identical otherwise you are overloading the method Must raise the same or fewer exceptions Can override/hide instance variables both variables will exist, but don t do it 39 Declared vs. Actual Types The actual type of an object is its allocated type Integer o = new Integer(1); A declared type is a type through which an object is being viewed Object o = new Integer(1); void m(object o) {... Each object always has one actual type, but can have many declared types 40 19
20 Method Dispatch Consider again o.m(arg1, arg2,..., argn); Only compiles if o s declared type contains an appropriate m method Invocation can depend on o s actual type 41 Dynamic Dispatch Example public class A { String f() { return I m an A! ; public class B extends A { String f() { return I m a B! ; public static void main(string args[]) { A a = new B(); B b = new B(); System.out.println(a.f() + b.f()); Prints I m a B! I m a B! 42 20
21 Self Reference this refers to the object the method is invoked on Thus can access fields of this object as this.x or this.y But more concise to omit super refers to the same object as this But used to access methods/variables in superclass 43 Example of super Call a superclass method from a subclass class Parent { int cost; void add(int x) { cost += x; class Child extends Parent { void add(int x) { if (x > 0) super.add(x); 44 21
22 Overloading Methods with the same name, but different parameters (count or types) are overloaded Invocation determined by name and types of params Not return value or exceptions Resolved at compile-time, based on declared types Be careful: Easy to inadvertently overload instead of override! 45 Overloading Example class Parent { int cost; void add(int x) { cost += x; void add(object s) throws NumberFormatException { cost += Integer.parseInt((String)s); class Child extends Parent { void add(string s) throws NumberFormatException { if (cost > 0) cost += Integer.parseInt(s); Child c = new Child(); Prints -1 c.add((object) -1 ); System.out.println(c.cost); 46 22
23 Static Fields and Methods static stored with the class Static fields allocated once, no matter how many objects created Static methods are not specific to any class instance, so cannot refer to this or super Can reference class variables and methods through either class name or an object ref Clearer to reference via the class name 47 Static Field Example Class definition Objects of class Foo Public class Foo { int foo; static int bar; int foo int foo Class implementation Foo int bar; int foo 48 23
24 Some Static Fields and Methods public static void main(string args[]) { public class Math { public final static PI = ; public class System { public static PrintStream out = ; 49 Static Method Dispatch Let B be a subclass of A, and suppose we have Then A a = new B(); Declared type A Actual type B Class (static) methods invoked on a will get the methods for the declared type A Invoking class methods via objects strongly discouraged Instead, invoke through class A.m() instead of a.m() 50 24
25 Static Method Dispatch Example public class A { static String g() { return This is A! ; public class B extends A { static String g() { return This is B! ; public static void main(string args[]) { A a = new B(); B b = new B(); System.out.println(a.g() + b.g()); Prints This is A! This is B! 51 Better Use of Static Methods public class A { static String g() { return This is A! ; public class B extends A { static String g() { return This is B! ; public static void main(string args[]) { System.out.println(A.g() + B.g()); Prints This is A! This is B! 52 25
26 Other Field Modifiers final can t be changed Must be initialized in declaration or in constructor transient, volatile Will cover later public, private, protected, package (default) Respectively, visible everywhere, only within this class, within same package or subclass, within same package 53 Other Method Modifiers final this method cannot be overridden Useful for security Allows compiler to inline method abstract no implementation provided Class must be abstract public visible outside this package native, synchronized Will cover later 54 26
27 Poor man s polymorphism Every object is a subtype of Object Thus, a data structure Set that implements sets of Objects can also hold Strings or images or anything! The trick is getting them back out: When given an Object, you have to downcast it 55 Downcasting (Bar) foo Run-time exception if object reference by foo is not a subtype of Bar Compile-time error if Bar is not a subtype of foo (i.e., it always throws an exception) No effect at run-time; just treats the result as if it were of type Bar o instanceof Foo returns true iff o is a subtype of Foo 56 27
28 Example class DumbSet { public void insert(object o) {.. public bool member(object o) {.. public Object any() {.. class MyProgram { public static void main(string[] args) { DumbSet set = new DumbSet(); String s1 = foo ; String s2 = bar ; set.insert(s1); set.insert(s2); System.out.println(s1+ in set? +set.member(s1)); String s = (String)set.any(); // downcast System.out.println( got +s); 57 Wrapper (Boxed) classes Integer, Boolean, Double, Are subclasses of Object Useful/required for polymorphic methods HashTable, LinkedList, Used in reflection classes Include many utility functions For example, convert to/from String 58 28
29 Array types Suppose S is a subtype of T then S[] is a subtype of T[] Object[] is a supertype of all arrays of reference types 59 Example: Object[] public class TestArrayTypes { public static void reversearray(object [] A) { for(int i=0, j=a.length-1; i<j; i++,j--) { Object tmp = A[i]; A[i] = A[j]; A[j] = tmp; public static void main(string [] args) { reversearray(args); for(int i=0; i < A.length; i++) System.out.println(args[i]); 60 29
30 Problem with Subtyping Arrays public class A {... public class B extends A { void newmethod();... void foo(void) { B[] bs = new B[]; A[] as = bs; 5.27// Since B[] subtype of A[] as[0] = new A(); // (1) bs[0].newmethod(); // (2) Program compiles without warning Java must generate run-time check at (1) to prevent (2) Type written to array must be subtype of declared type 61 Java Classes and Objects Each object is an instance of a class An array is an object Each class extends one superclass Object if not specified Class Object has no superclass 62 30
31 Objects Have Methods All objects, therefore, inherit them Default implementations may not be the ones you want public boolean equals (Object that) conceptual equality public String tostring() returns printable representation public int hashcode() key for hash table public void finalize() called if object is garbage collected And others 63 Equality Object.equals(Object) method Structural ( conceptual ) equality == operator (!= as well) True if arguments reference the same object o == p implies o.equals(p) 64 31
32 Overriding Equals class Foo { public boolean equals(foo f) { // wrong! class Foo { public boolean equals(object o) { if (!(o instanceof Foo)) return false;... // right! The first case creates an overloaded method, while the second overrides the parent (Object) method. 65 Overriding hashcode hashcode() is used for objects that may be stored in hash table Rule of thumb: If you override equals() or hashcode(), you should also override the other a.equals(b) implies a.hashcode() == b.hashcode() 66 32
33 Preconditions Functions often have requirements on their inputs // Return maximum element in A[i..j] int findmax(int[] A, int i, int j) {... A is non-empty i and j must be non-negative i and j must be less than A.length i < j (maybe) These are called preconditions or requires clauses 67 Dealing with Errors What do you do if a precondition isn t met? What do you do if something unexpected happens? Try to open a file that doesn t exist Try to write to a full disk 68 33
34 Signaling Errors Style 1: Return invalid value // Returns value key maps to, or null if no // such key in map Object get(object key); Disadvantages? 69 Signaling Errors (cont d) Style 2: Return an invalid value and status static int lock_rdev(mdk_rdev_t *rdev) {... if (bdev == NULL) return -ENOMEM;... // Returns NULL if error and sets global // variable errno FILE *fopen(const char *path, const char *mode); 70 34
35 Problems with These Approaches What if all possible return values are valid? E.g., findmax from earlier slide What if client forgets to check for error? No compiler support What if client can t handle error? Needs to be dealt with at a higher level 71 Exceptions in Java On an error condition, we throw an exception At some point up the call chain, the exception is caught and the error is handled Separates normal from error-handling code A form of non-local control-flow Like goto, but structured 72 35
36 Throwing an Exception Create a new object of the class Exception, and throw it if (i >= 0 && i < a.length ) return a[i]; else throw new ArrayIndexOutOfBounds(); Exceptions thrown are part of return type When overriding method in superclass, cannot throw any more exceptions than parent s version 73 Method throws declarations A method declares the exceptions it might throw public void opennext() throws UnknownHostException, EmptyStackException { Must declare any exception the method might throw Unless it is caught in (masked by) the method Includes exceptions thrown by called methods Certain kinds of exceptions excluded 74 36
37 Exception Handling All exceptions eventually get caught First catch with supertype of the exception catches it finally is always executed try { if (i == 0) return; mymethod(a[i]); catch (ArrayIndexOutOfBounds e) { System.out.println( a[] out of bounds ); catch (MyOwnException e) { System.out.println( Caught my error ); catch (Exception e) { System.out.println( Caught + e.tostring()); throw e; finally { /* stuff to do regardless of whether an exception */ /* was thrown or a return taken */ 75 Masking Exceptions Handle exception and continue while ((s =...)!= null) { try { FileInputStream f = new FileInputStream(s);... catch (FileNotFoundException e) { System.out.println(s + not found ); 76 37
38 Reflecting Exceptions Pass exception up to higher level Automatic support for throwing same exception Sometimes useful to throw different exception try {... a[5]... catch (IndexOutOfBoundsException e) { throw new EmptyException( Arrays.min ); 77 Exception Chaining Indicate the cause of a thrown exception Specify the exception that caused this one Shows cause chain in stack trace try {... a[0]... catch (IndexOutOfBoundsException e) { // e can be retrieved from exn with getcause() throw new Exception( Arrays.min, e); 78 38
39 Exception Hierarchy Throwable Checked Error Exception Unchecked RuntimeException 79 Unchecked Exceptions Subclasses of RuntimeException and Error are unchecked Need not be listed in method specifications Currently used for things like NullPointerException IndexOutOfBoundsException VirtualMachineError Why aren t all Exceptions and Errors checked? 80 39
CMSC433, Fall 2008 Programming Language Technology and Paradigms. Java Review. Adam Porter 9/4/08
CMSC433, Fall 2008 Programming Language Technology and Paradigms Java Review Adam Porter 9/4/08 Java Descended from Simula67, SmallTalk, others Superficially similar to C, C++ Fully specified, compiles
More informationAdministrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments
CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised
More informationPreconditions. CMSC 330: Organization of Programming Languages. Signaling Errors. Dealing with Errors
Preconditions Functions often have requirements on their inputs // Return maximum element in A[i..j] int findmax(int[] A, int i, int j) {... A is nonempty Aisn't null iand j must be nonnegative iand j
More informationInput, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003
Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Exceptions Parameter Passing Preconditions Functions often have requirements on their inputs // Return maximum element in A[i..j] int findmax(int[] A, int
More informationCMSC 330: Organization of Programming Languages. Polymorphism
CMSC 330: Organization of Programming Languages Polymorphism An Integer Stack Implementation class Stack { class Entry { Integer elt; Entry next; Entry(Integer i, Entry n) { elt = i; next = n; } } Entry
More informationSri Vidya College of Engineering & Technology Question Bank
1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationPolymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism
CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø
More informationCH. 2 OBJECT-ORIENTED PROGRAMMING
CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED
More informationCS 231 Data Structures and Algorithms, Fall 2016
CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 30 November 13, 2015 ExcepEons / IO Chapter 27 HW7: PennPals Chat Due: Tuesday, November 17 th Announcements Start today if you haven't already! Poll
More information40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the
Answers 1) B 2) C 3) A 4) D 5) Non-static members 6) Static members 7) Default 8) abstract 9) Local variables 10) Data type default value 11) Data type default value 12) No 13) No 14) Yes 15) No 16) No
More informationA Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1
A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 30 April 4, 2018 I/O & Histogram Demo Chapters 28 HW7: Chat Server Announcements No penalty for late submission by tomorrow (which is a HARD deadline!)
More information15CS45 : OBJECT ORIENTED CONCEPTS
15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
More informationCHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA
1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created
More informationContents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
More informationGetting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park
Getting Started in Java Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park Hello, World In HelloWorld.java public class HelloWorld { public static void main(string [] args) { System.out.println(
More informationF1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept
F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming
More informationFull file at Chapter 2 - Inheritance and Exception Handling
Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a
More informationJava in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationClass definition. complete definition. public public class abstract no instance can be created final class cannot be extended
JAVA Classes Class definition complete definition [public] [abstract] [final] class Name [extends Parent] [impelements ListOfInterfaces] {... // class body public public class abstract no instance can
More informationCS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?
CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look
More informationLanguage Features. 1. The primitive types int, double, and boolean are part of the AP
Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More information20 Most Important Java Programming Interview Questions. Powered by
20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (IS120) Lecture 30 April 4, 2016 Exceptions hapter 27 HW7: PennPals hat Due: Tuesday Announcements Simplified Example class { public void foo() {.bar(); "here in foo");
More informationCISC 323 (Week 9) Design of a Weather Program & Java File I/O
CISC 323 (Week 9) Design of a Weather Program & Java File I/O Jeremy Bradbury Teaching Assistant March 8 & 10, 2004 bradbury@cs.queensu.ca Programming Project The next three assignments form a programming
More informationInput-Output and Exception Handling
Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Reading and writing text files Exceptions The try block catch and finally
More informationBIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic
BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines
More informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
More informationObject Oriented Design. Object-Oriented Design. Inheritance & Polymorphism. Class Hierarchy. Goals Robustness Adaptability Flexible code reuse
Object-Oriented Design Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented Design 1 March 2005 Object Oriented
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationLab 2: File Input and Output
Lab 2: File Input and Output This lab introduces how to handle files as both input and output. We re coming back to Tracery (which you implemented in Lab 1) with this assignment but instead of always reading
More informationDay 4. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information
More informationCOMP1008 Exceptions. Runtime Error
Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationCS 3 Introduction to Software Engineering. 3: Exceptions
CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction
More informationIndex COPYRIGHTED MATERIAL
Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes
More informationObject-Oriented Design. March 2005 Object Oriented Design 1
Object-Oriented Design March 2005 Object Oriented Design 1 Object Oriented Design Goals Robustness Adaptability Flexible code reuse Principles Abstraction Encapsulation Modularity March 2005 Object Oriented
More informationJava Intro 3. Java Intro 3. Class Libraries and the Java API. Outline
Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries
More informationByte and Character Streams. Reading and Writing Console input and output
Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 26 March 23, 2016 Inheritance and Dynamic Dispatch Chapter 24 Inheritance Example public class { private int x; public () { x = 0; } public void incby(int
More informationTirgul 1. Course Guidelines. Packages. Special requests. Inner classes. Inner classes - Example & Syntax
Tirgul 1 Today s topics: Course s details and guidelines. Java reminders and additions: Packages Inner classes Command Line rguments Primitive and Reference Data Types Guidelines and overview of exercise
More informationCS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)
CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers
More informationContents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix
PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring
More informationBuilding Java Programs. Inheritance and Polymorphism
Building Java Programs Inheritance and Polymorphism Input and output streams stream: an abstraction of a source or target of data 8-bit bytes flow to (output) and from (input) streams can represent many
More informationType Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004
Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...
More informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
More informationC++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.
CMSC433, Fall 2001 Programming Language Technology and Paradigms Adam Porter Sept. 4, 2001 C++ without Classes Don t need to say struct New libraries function overloading confusing link messages default
More informationWA1278 Introduction to Java Using Eclipse
Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java
More informationInheritance and Polymorphism
Inheritance and Polymorphism Dr. M. G. Abbas Malik Assistant Professor Faculty of Computing and IT (North Jeddah Branch) King Abdulaziz University, Jeddah, KSA mgmalik@kau.edu.sa www.sanlp.org/malik/cpit305/ap.html
More informationException-Handling Overview
م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationCSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige
CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors
More informationHere is a hierarchy of classes to deal with Input and Output streams.
PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data
More informationChapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,
Chapter 11 Inheritance and Polymorphism 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the best way to design
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationSoftware Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)
Software Development & Education Center Java Platform, Standard Edition 7 (JSE 7) Detailed Curriculum Getting Started What Is the Java Technology? Primary Goals of the Java Technology The Java Virtual
More informationDeclarations and Access Control SCJP tips
Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for
More informationCS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun
CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what
More informationCOMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions
COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
More informationOOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.
OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every
More informationCS-202 Introduction to Object Oriented Programming
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction
More informationExceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages
References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/
More informationComputer Science II (20073) Week 1: Review and Inheritance
Computer Science II 4003-232-01 (20073) Week 1: Review and Inheritance Richard Zanibbi Rochester Institute of Technology Review of CS-I Hardware and Software Hardware Physical devices in a computer system
More informationneeds to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine
Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as
More informationCS 251 Intermediate Programming Java I/O Streams
CS 251 Intermediate Programming Java I/O Streams Brooke Chenoweth University of New Mexico Spring 2018 Basic Input/Output I/O Streams mostly in java.io package File I/O mostly in java.nio.file package
More informationCharacter Stream : It provides a convenient means for handling input and output of characters.
Be Perfect, Do Perfect, Live Perfect 1 1. What is the meaning of public static void main(string args[])? public keyword is an access modifier which represents visibility, it means it is visible to all.
More informationInheritance (Part 5) Odds and ends
Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there
More informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
More informationInheritance (continued) Inheritance
Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationFundamentals of Object Oriented Programming
INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of
More informationExceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationIntroductory Programming Exceptions and I/O: sections
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationCasting -Allows a narrowing assignment by asking the Java compiler to "trust us"
Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:
More informationIntroduction to Java https://tinyurl.com/y7bvpa9z
Introduction to Java https://tinyurl.com/y7bvpa9z Eric Newhall - Laurence Meyers Team 2849 Alumni Java Object-Oriented Compiled Garbage-Collected WORA - Write Once, Run Anywhere IDE Integrated Development
More informationCS 61B Discussion 5: Inheritance II Fall 2014
CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation
More informationProgramming Languages and Techniques (CIS120)
Programming Languages and Techniques (CIS120) Lecture 24 October 29, 2018 Arrays, Java ASM Chapter 21 and 22 Announcements HW6: Java Programming (Pennstagram) Due TOMORROW at 11:59pm Reminder: please complete
More informationWhat is it? CMSC 433 Programming Language Technologies and Paradigms Spring Approach 1. Disadvantage of Approach 1
CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Singleton Pattern Mar. 13, 2007 What is it? If you need to make sure that there can be one and only one instance of a class. For example,
More informationExceptions. CSE 142, Summer 2002 Computer Programming 1.
Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»
More informationExceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.
Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented
More information09-1. CSE 143 Java GREAT IDEAS IN COMPUTER SCIENCE. Overview. Data Representation. Representation of Primitive Java Types. Input and Output.
CSE 143 Java Streams Reading: 19.1, Appendix A.2 GREAT IDEAS IN COMPUTER SCIENCE REPRESENTATION VS. RENDERING 4/28/2002 (c) University of Washington 09-1 4/28/2002 (c) University of Washington 09-2 Topics
More informationNational University. Faculty of Computer Since and Technology Object Oriented Programming
National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes
More informationLecture 19 Programming Exceptions CSE11 Fall 2013
Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:
More information1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java
Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as
More informationPoints To Remember for SCJP
Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the
More informationExceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws
Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,
More information