Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.

Slides:



Advertisements
Similar presentations
Stacks.
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Lecture 2: Object Oriented Programming I
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 CSCD 326 Data Structures I Stacks. 2 Data Type Stack Most basic property: last item in (most recently inserted) is first item out LIFO - last in first.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Classes, Types and Objects Data Structures Chapter 1 Prof. Vidya Manian Dept. of Electrical and Comptuer Engineering ICOM 4035Java Programming BasicsECE,
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Programming Principles Data types and Variables. Data types Variables are nothing but reserved memory locations to store values. This means that when.
Multiple Choice Solutions True/False a c b e d   T F.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 1 Specific topics of the Java Language Related to This Class Classes and.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
The Java Programming Language
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.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
© 2004 Goodrich, Tamassia Stacks. © 2004 Goodrich, Tamassia Stacks2 Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
1 Basic Java Constructs and Data Types – Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
COM S 228 Introduction to Data Structures Instructor: Ying Cai Department of Computer Science Iowa State University Office: Atanasoff.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Exam 2 EXAM 2 Thursday!!! 25% of Final Grade Know: loops, switch/case Files Input failure (e.g. scan.hasNextInt())
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Classes and Objects. Primitives Single-valued data items. Not Objects byte8-bit signed two's complement integer short16-bit signed two's complement integer.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Java: Base Types All information has a type or class designation
Topic: Classes and Objects
Objects as a programming concept
3 Introduction to Classes and Objects.
Java: Base Types All information has a type or class designation
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Programming Language Concepts (CIS 635)
null, true, and false are also reserved.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Chap 2. Identifiers, Keywords, and Types
Arrays Arrays are represented by objects but there is no class that array objects are instances of. Variables of array type are declared using bracket.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Corresponds with Chapter 5
Presentation transcript:

Chap. 1 Classes, Types, and Objects

How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions go here… }

A simple example template for a class definition without these optional clauses is as follows: class Gnome { // instance variable definitions would go here … // method definitions would go here … }

Class Modifiers abstract: describes a class that has abstract methods.  Abstract methods are declared with the abstract keyword and are empty.  A class that has nothing but abstract methods and no instance variables is more properly called an interface.  An abstract class usually has a mixture of abstract methods and actual methods.

An Example of Abstract Class public abstract class EulerTour { protected BinaryTree tree; // Execution of the traversal. This abstract method must be specified in a concrete subclass public abstract Object execute(BinaryTree T); protected void init(BinaryTree T) { tree = T; } … }

An Example of Interface public interface Stack { // return the number of elements in the stack public int size(); // return whether the stack is empty public boolean isEmpty(); // Inspect the element at the top of the stack public Object top() throws EmptyStackException; // Insert an element at the top of the stack public void push (Object element); // Remove the top element from the stack public Object pop() throws EmptyStackException; }

final: describes a class that can have no subclass. public: describes a class that can be instantiated or extended by anything in the same package or by anything that imports the class.  All public classes are declared in their own separate file called.java.  There can only be one public class per file.  If the public class modifier is not used, the class in considered friendly. This means that it can be used and instantiated by all classes in the same package. This is the default class modifier.

Base Types booleanBoolean value: true or false char16-bit Unicode character byte8-bit signed two’s complement integer short16-bit signed two’s complement integer int32-bit signed two’s complement integer long64-bit signed two’s complement integer float32-bit floating-point number (IEEE ) double64-bit floating-point number (IEEE )

Objects = new ([param, param,…]); myPoint = new Point(3,6);

Number Objects Base TypeClass NameCreation ExampleAccess Example byteByten = new Byte((byte)34);n.byteValue() shortShortn = new Short((short)100);n.shortValue() intIntegern = new Integer(1045);n.intValue() longLongn = new Long(10849L);n.longValue() floatFloatn = new Float(3.934F);n.floatValue() doubleDoublen = new Double(3.934);n.doubleValue()

String Objects String concatenation String s = “kilo” + “meters”;

Instance Variables Syntax: [ ] [= ]; class Gnome { // instance variables; protected String name; protected int age; protected Gnome gnome_buddy; private boolean magical; public double height = 2.6; // an initialization public static final int MAX_HEIGHT = 3; // a constant // Methods definitions would go here… }

Variable Modifiers public: anyone can access public instance variables. protected: only methods of the same package or of subclass can access. private: only methods of the same class (not methods of a subclass) can access. If none is used, the instance variable is friendly. It can be accessed by any class in the same package.

static: is used to declare that a variable is associated with the class, not with individual instances of that class. Static variables are used to store “global” information about a class. final: a final instance variable is one that must be assigned an initial value, and then can never be assigned a new value after that.

Methods Syntax: [ ] ([ ]) { // method body … } has the syntax: [, [, …] ]

Example: Public void renameGnome(String s) { name = s; // Reassign the name instance variable of this gnome. }

Method Modifiers public: anyone can call public methods. protected: only methods of the same package or of subclasses can call a protected method. private: only methods of the same class (not methods of a subclass) can call a private method. If none is used, the method is friendly. Friendly methods can only be called by objects of classes in the same package.

The above method modifiers can be followed by the following to further restrict a method: abstract: an abstract method has no code. It only appears within an abstract class.  example:  public abstract void setHeight (double newHeight);

final: this is a method that cannot be overridden by a subclass. static: this is a method that is associated with the class itself, and not with a particular instance of the class.  Static methods can also be used to change the state of static variables associated with a class (provided these variables are not declared to be final).

Return Types If the method returns a value, it is called a function. If the method returns a void, it is called a procedure. Example: public boolean isMagical( ) { return magical; }

Parameters All parameters in Java are passed by value. The method can change the copy but not the original. If we pass an object reference as a parameter to a method, the reference is copied as well.

Constructor Methods A constructor is used to initialized newly created objects. [constructor_modifiers] ([ ]) { // constructor body … } A constructor has no return value. An abstract, static, or final constructor is not allowed.

For example: public Fish (int w, String n) { weight = w; name = n; } Fish myFish = new Fish (7, “Wally”);

The Main Method public static void main(String[ ] args) { // main method body … } Invoke the program by typing: java Aquarium 45 Args[0] is 45.

Complete example of the Gnome class public class Gnome { // instance variables protected String name; protected int age; protected Gnome gnome_buddy; private boolean magical = false; public double height = 2.6; // in feet public static final int MAX_HEIGHT = 3; // maximum height

// Constructors: Gnome (String nm, int ag, Gnome bud, double hgt) { // fully parameterized name = nm; age = ag; gnome_buddy = bud; height = hgt; }

Gnome( ) { // Default constructor name = “Rumple”; age = 204; gnome_buddy = null; height = 2.1; }

// Methods public static void makeKing (Gnome h) { h.name = “King ” + h.getRealName( ); h.magical = true; // Only the Gnome class can reference this field. } pubic void makeMeKing( ) { name = “King “+ getRealName( ); magical = true; }

public boolean isMagical( ) {return magical;} public void setHeight (int newHeight) { height = newHeight; } public String getName ( ) {return “I won’t tell!”; } public String getRealName( ) { return name; } public void renameGnome (String s) { name = s; }

Expressions String Concatenation String rug = “carpet”; String dog = “spot”; String mess = rug + dog; String answer = mess + “ will cost me “ “ dollars!”; Result: “carpetspot will cost me 5 dollars!”

Implicit Casting with String Objects String s = (String) 4.5; // wrong String t = “Value = “ + (String)13; // wrong String u = 22; // wrong String s = “ “ + 4.5; // correct, but poor style String t = “Value = “ + 13; // good String u = Integer.toString(22); // good

Arrays To find the size of an array:.length // count the number of times an integer x appears in an array a public static int countInteger (int [ ] a, int x) { int count = 0; for (int i = 0; i < a.length; i++) { if (a[i] != x) continue; count ++; } return count; }

The syntax for declaring an array: [ ] [= {,, …, }]; The syntax for creating an array: new [ ] int [ ] a = new int [10]; float [ ] [ ] x = new float [8][10];

Simple Input and Output Simple Output Methods System.out.print(“Java values: “); System.out.print(3.1415); System.out.print(‘,’); System.out.print(15); System.out.println(“ (double, char, int).”); Result: Java values: , 15 (double, char, int).

Simple Input Methods int read( ): read a single char. String readLine( ): read a line of text up to the next newline character. Example: java.io.BufferedReader stndin; // Standard input (buffered) String line; // A line of input text double sum, d = 0.0; int i = 0; stndin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

System.out.print(“Input a double: “); System.out.flush( ); // clears the input stream if ((line = stndin.readLine( )) != null) d = Double.valueOf(line).doubleValue( ); System.out.print(“Input an int: “); System.out.flush( ); if ((line = stndin.readLine( ))!= null) i = Integer.valueOf(line).intValue( ); sum = d + i; System.out.println(“Their sum is “ + sum + “.”);

Result: Input a double: Input an int: 209 Their sum is