Java Language Quick-Reference Guide B. Oracle10g: Java Programming B - 2 Console Output Java applications and applets can output simple messages to the.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

Object Oriented Programming with Java
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Data Structures Lecture 2 Fang Yu Department of Management Information Systems National Chengchi University Fall 2011.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Written by: Dr. JJ Shepherd
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Final Review.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
1 More on Threads b b A section of code executed independently of other threads written within a single program. b b Java threads can access global data;
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
1 Java - Threads A thread is an individual flow of control within a larger program. A program which is running more than one thread is said to be multithreaded.
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 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Chapter 10 Classes Continued
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Programming Languages and Paradigms Object-Oriented Programming.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
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 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Introduction to Java Prepared by: Ahmed Hefny. Outline Classes Access Levels Member Initialization Inheritance and Polymorphism Interfaces Inner Classes.
The Java Programming Language
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control.
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.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Written by: Dr. JJ Shepherd
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
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.
Modern Programming Tools And Techniques-I
Packages, Interfaces & Exception Handling
Extending Classes.
Java Programming Language
Conditional Statements
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Chap 2. Identifiers, Keywords, and Types
Final and Abstract Classes
Chapter 11 Inheritance and Encapsulation and Polymorphism
INTERFACES Explained By: Sarbjit Kaur. Lecturer, Department of Computer Application, PGG.C.G., Sector: 42, Chandigarh.
Presentation transcript:

Java Language Quick-Reference Guide B

Oracle10g: Java Programming B - 2 Console Output Java applications and applets can output simple messages to the console as follows: System.out.println("This is displayed on the console"); Data Types Operators

Oracle10g: Java Programming B - 3 Control Flow: if … else if statements are formed as follows (the else clause is optional). The braces {} are necessary if the if-body exceeds one line; even if the if-body is just one line, the braces {} are worth having to aid readability: String dayname; … if (dayname.equals("Sat") || dayname.equals("Sun")){ System.out.println("Hooray for the weekend"); } else if (dayname.equals("Mon")) { System.out.println("I dont like Mondays"); } else { System.out.println("Not long for the weekend!"); } Control Flow: switch switch is used to check an integer (or character) against a fixed list of alternative values: int daynum; … switch (daynum) { case 0: case 6: System.out.println("Hooray for the weekend"); break; case 1: System.out.println("I dont like Mondays"); break; default: System.out.println("Not long for the weekend!"); break; }

Oracle10g: Java Programming B - 4 Control Flow: Loops Java contains three loop mechanisms: int i = 0; while (i < 100) { System.out.println("Next square is: " + i*i); i++; } for (int i = 0; i < 100; i++) { System.out.println("Next square is: " + i*i); } int positiveValue; do { positiveValue = getNumFromUser(); } while (positiveValue < 0);

Oracle10g: Java Programming B - 5 Defining Classes When you define a class, you define the data attributes (usually private ) and the methods (usually public ) for a new data type. The class definition is placed in a.java file as follows: // This file is Student.java. The class is declared // public, so that it can be used anywhere in the program public class Student { private String name; private int numCourses = 0; // Constructor to initialize all the data members public Student(String n, int c) { name = n; numCourses = c; } // No-arg constructor, to initialize with defaults public Student() { this("Anon", 0); // Call other constructor } // finalize() is called when obj is garbage collected public void finalize() { System.out.println("Goodbye to this object"); } // Other methods public void attendCourse() { numCourses++; } public void cancelPlaceOnCourse() { numCourses--; } public boolean isEligibleForChampagne() { return (numCourses >= 3); } }

Oracle10g: Java Programming B - 6 Using Classes To create an object and send messages to the object: public class MyTestClass { public static void main(String[] args) { // Step 1 - Declare object references // These refer to null initially in this example Student me, you; // Step 2 - Create new Student objects me = new Student("Andy", 0); you = new Student(); // Step 3 - Use the Student objects me.attendCourse(); you.attendCourse(); if (me.isEligibleForChampagne()) System.out.println("Thanks very much"); } }

Oracle10g: Java Programming B - 7 Arrays An array behaves like an object. Arrays are created and manipulated as follows: // Step 1 - Declare a reference to an array int[] squares; // Could write int squares[]; // Step 2 - Create the array "object" itself squares = new int[5];// Creates array with 5 slots // Step 3 - Initialize slots in the array for (int i=0; i < squares.length; i++) { squares[i] = i * i; System.out.println(squares[i]); } Note that array elements start at [0], and that arrays have a length property that gives you the size of the array. If you inadvertently exceed an arrays bounds, an exception is thrown at run time and the program aborts. Note: Arrays can also be set up by using the following abbreviated syntax: String[] cities = { "San Francisco", "Dallas", "Minneapolis", "New York", "Washington, D.C." };

Oracle10g: Java Programming B - 8 Inheritance and Polymorphism A class can inherit all of the data and methods from another class. Methods in the superclass can be overridden by the subclass. Any members of the superclass that you want to access in the subclass must be declared protected. The protected access specifier allows subclasses, plus any classes in the same package, to access that item. public class Account { private double balance = 0.0; public Account(double initBal) { balance = initBal; } public void deposit(double amt) { balance += amt; } public void withdraw(double amt) { balance -= amt; } public void display() { System.out.println("Balance is: " + balance); } } public class CheckAccount extends Account { private int maxChecks = 0; private int numChecksWritten = 0; public CheckAccount(double initBal, int maxChk) { super(initBal);// Call superclass ctor maxChecks = maxChk;// Initialize our data } public void withdraw(double amt) { super.withdraw(amt);// Call superclass numChecksWritten++;// Increment chk. num. } public void display() { super.display();// Call superclass System.out.println(numChecksWritten); } }

Oracle10g: Java Programming B - 9 Abstract Classes An abstract class is one that can never be instantiated; in other words, you cannot create an object of such a class. Abstract classes are specified as follows: // Abstract superclass public abstract class Mammal { … } // Concrete subclasses public class Cat extends Mammal { … } public class Dog extends Mammal { … } public class Mouse extends Mammal { … }

Oracle10g: Java Programming B - 10 Abstract Methods An abstract method is one that does not have a body in the superclass. Each concrete subclass is obliged to override the abstract method and provide an implementation; otherwise, the subclass is itself deemed abstract because it does not implement all its methods. // Abstract superclass public abstract class Mammal { // Declare some abstract methods public abstract void eat(); public abstract void move(); public abstract void reproduce(); // Define some data members if you like private double weight; private int age; // Define some concrete methods too if you like public double getWeight{} { return weight; } public int getAge() { return age; } }

Oracle10g: Java Programming B - 11 Interfaces An interface is similar to an abstract class with 100% abstract methods and no instance variables. An interface is defined as follows: public interface Runnable { public void run(); } A class can implement an interface as follows. The class is obliged to provide an implementation for every method specified in the interface; otherwise, the class must be declared abstract because it does not implement all its methods. public class MyApp extends Applet implements Runnable { public void run() { // This is called when the Applet is kicked off // in a separate thread … } // Plus other applet methods … }

Oracle10g: Java Programming B - 12 Static Variables A static variable is like a global variable for a class. In other words, you get only one instance of the variable for the whole class, regardless of how many objects exist. static variables are declared in the class as follows: public class Account { private String accnum; // Instance var private double balance = 0.0; // Instance var private static double intRate = 5.0; // Class var … } Static Methods A static method in a class is one that can access only static items; it cannot access any non- static data or methods. static methods are defined in the class as follows: public class Account { public static void setIntRate(double newRate) { intRate = newRate; } public static double getIntRate() { return intRate; } … } To invoke a static method, use the name of the class as follows: public class MyTestClass { public static void main(String[] args) { System.out.println("Interest rate is" + Account.getIntRate()); } }

Oracle10g: Java Programming B - 13 Packages Related classes can be placed in a common package as follows: // Car.java package mycarpkg; public class Car { … } // Engine.java package mycarpkg; public class Engine { … } // Transmission.java package mycarpkg; public class Transmission { … } Importing Packages Anyone needing to use the classes in this package can import all or some of the classes in the package as follows: import mycarpkg.*; // import all classes in package or import mycarpkg.Car; // just import individual classes

Oracle10g: Java Programming B - 14 The final Keyword The final keyword can be used in three situations: final classes (for example, the class cannot be inherited from) final methods (for example, the method cannot be overridden in a subclass) final variables (for example, the variable is constant and cannot be changed) Here are some examples: // final classes public final class Color { … } // final methods public class MySecurityClass { public final void validatePassword(String password) { … } } // final variables public class MyTrigClass { public static final double PI = ; … }

Oracle10g: Java Programming B - 15 Exception Handling Exception handling is achieved through five keywords in Java: try The block of code where statements that can cause an exception are placed catch The block of code where error processing is placed finally An optional block of code after a try block, for unconditional execution throw The keyword that is used in the low-level code to generate or throw an exception throws The keyword that specifies the list of exceptions that a method can throw Here are some examples: public class MyClass { public void anyMethod() { try { func1(); func2(); func3(); } catch (IOException e) { System.out.println("IOException:" + e); } catch (MalformedURLException e) { System.out.println("MalformedURLException:" + e); } finally { System.out.println("This is always displayed"); } } public void func1() throws IOException { … } public void func2() throws MalformedURLException { … } public void func3() throws IOException, MalformedURLException { … } }