Classes and Objects
Upcoming SlideShare
Loading in...5
×
 

Classes and Objects

on

  • 1,484 views

Java Classes and Objects

Java Classes and Objects

Statistics

Views

Total Views
1,484
Views on SlideShare
1,484
Embed Views
0

Actions

Likes
2
Downloads
63
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Classes and Objects Classes and Objects Presentation Transcript

  • Introduction To Java Programming
  • What is OOP?
    • Object-oriented programming technology can be summarized by three key concepts:
    • – Objects that provide encapsulation of procedures and data
    • – Messages that support polymorphism across objects
    • – Classes that implement inheritance within class hierarchies
  • The Three OOP Principles
    • Encapsulation
    • The mechanism that binds together code and the data it manipulates, and both safe from outside interference and misuse
    • Inheritance
    • The process by which one object acquires the properties of another object
    • Polymorphism
      • A feature that allows one interface to be used for a general class of actions.
  • History of Java
    • During 1990, James Gosling, Bill Joy and others at Sun Microsystems began developing a language called Oak.
    • They primarily intended it as a language for microprocessors embedded in consumer devices.
    • To serve these goals, Oak needed the following features:
    • _ platform independence, since it must run on devices from multiple manufacturers
    • _ extreme reliability (can’t expect consumers to reboot their VCRs!)
    • _ compactness, since embedded processors typically have limited memory
  • History of Java (continued..)
    • Sun Microsystems shifted the target market to internet applications and changed the name of the project to Java .
    • The portability of Java made it ideal for the Web, and in 1995 Sun’s HotJava browser appeared.
    • It illustrated the power of applets – programs that run within a browser – and the ability of Java to accelerate program development.
  • History of Java (continued..)
    • Java is used extensively in business to develop enterprise, or middleware, applications such as on-line stores, transactions processing, dynamic web page generation, and database interactions .
    • Java has also returned to its Oak roots and become very common on small platforms such as smart cards, cell phones, and PDAs.
    • For example, as of mid-2004 there are over 350 different Java-enabled mobile phone handsets available across the world, and over 600 million Java Cards have been distributed.
  • Comparing C++ and Java
    • Some of the important features that distinguish Java from C++.
    • Everything must be in a class. There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within a class.
    • There are no structs or enumerations or unions, only classes.
    • All method definitions are defined in the body of the class
    • Class definitions are roughly the same form in Java as in C++, but there’s no closing semicolon
  • Comparing C++ and Java (continued..)
    • In addition, package names are established using the dot, and to perform a kind of C++ #include you use the import keyword.
    • There are no Java pointers in the sense of C and C++
    • There are no destructors in Java. The lifetime of an object is determined instead by the garbage collector
    • There is a finalize( ) method that’s a member of each class, something like a C++ destructor, but finalize( ) is called by the garbage collector and is supposed to be responsible only for releasing "resources" (such as open files, sockets, ports, URLs, etc)
  • What is Java?
    • Java is a high-level, third generation programming language, like C, Fortran, Smalltalk, Perl, and many others.
    • We can use Java to write computer applications that crunch numbers, process words, play games, store data or do any of the thousands of other things computer software can do.
  • Java isn't C!
    • In C, almost everything is in functions
    • In Java, almost everything is in classes
    • There is often only one class per file
    • There must be only one public class per file
    • The file name must be the same as the name of that public class, but with a .java extension
  • Java Virtual Machine
    • Java is compiled into bytecodes
    • Bytecodes are high-level, machine-independent instructions for a hypothetical machine, the Java Virtual Machine (JVM)
    • The Java run-time system provides the JVM
  • Java Virtual Machine (contonued..)
    • The JVM interprets the bytecodes during program execution
    • Since the bytecodes are interpreted, the performance of Java programs slower than comparable C/C++ programs
    • But the JVM is continually being improved and new techniques are achieving speeds comparable to native C++ code
  • Java Virtual Machine (contonued..)
    • All Java programs run on top of the JVM
    • The JVM was first implemented inside Web browsers, but is now available on a wide variety of platforms
    • The JVM interprets the bytecodes defined in a machine-independent binary file format called a class file
  • Compiling and Executing A Java Program
    • On command line
      • javac file.java
    • On command line
      • java classname
  • Java Features
    • Automatic garbage collection
    • No manual memory allocation and deallocation
      • Never have to worry about memory leaks
    • No pointers or pointer arithmetic
    • Arrays are first-class objects
    • Array bounds are always checked
    • Multiple inheritance replaced by interfaces
    • Eliminates complexities of multiple inheritance
  • Types Of Java Programs
    • Application
    • Standalone Java program that can run independent of any Web browser
    • Applet
    • Java program that runs within a Java-enabled Web browser
    • Servlet
    • Java software that is loaded into a Web server to provide additional server functionality ala CGI programs
  • Automatic garbage collection
    • In some languages the programmer allocates memory for the creation of objects stored on the heap and the responsibility of later deallocating that memory thus resides on the programmer
    • If the programmer forgets to deallocate memory or writes code that fails to do so, a memory leak occurs and the program can consume an arbitrarily large amount of memory
  • Automatic garbage collection (continued..)
    • In Java, this potential problem is avoided by automatic garbage collection
    • The programmer determines when objects are created, and the Java runtime is responsible for managing the object's lifecycle
    • The program or other objects can reference an object by holding a reference to it
    • When no references to an object remain, the Java garbage collector automatically deletes the unreachable object , freeing memory and preventing a memory leak
  • Java as a General Application Language
    • Java is a powerful, general-purpose programming language that just happens to be safe and architecture independent
    • Standalone Java applications are not subject to the restrictions; they can do all activities that software written in a language like C does
    • Any software that implements the Java run-time system can run Java applications.
    • Applications written in Java can be large or small, standalone or component-like, as in other languages
  • Anatomy of a Java Program
    • Comments
    • Package
    • Reserved words
    • Modifiers
    • Statements
    • Blocks
    • Classes
    • Methods
    • The main method
  • Java Comments
    • Java supports three styles of comments:
    • A standard C-style comment, where all of the characters between
    • /* and */ are ignored.
    • A single-line comment, where all of the characters from
      • // to the end of the line are ignored.
    • A documentation comment that begins with
      • /** and ends with */.
  • Packages
    • Java classes can be grouped together into a package
    • Packages have several advantages:
    • related classes can be grouped together
    • class names and member names need not be unique across the entire program
    • members can be accessible only to methods of classes in the same package
    • The package statement must appear as the first statement of the Java source file:
    • package Myproject.Mymodule.Myclasses;
    • If no package statement is present, the code is made part of the unnamed default package
  • Packages (continued..)
    • A fully qualified Java name for a class is:
    • <Package Name>.<Class Name>
    • For example, Myproject.Mymodule.Myclasses.Myclass
    • Class files must be stored in a directory that has the same components of the package name for the class
    • For example, the class Myproject.Mymodule.Myclasses.Myclass must be in the Myproject / Mymodule / Myclasses / Myclass . class file
    • This filename is interpreted relative to one of the directories specified in the CLASSPATH environment variable
  • The Import Statement
    • The import statement allows the use of abbreviated class names in a Java source file
    • Classes are always available via their fully-qualified names:
    • Myproject.Mymodule.Myclasses.Myclass mc = new Myproject.Mymodule.Myclasses.Myclass ();
    • The import statement does not &quot;read in&quot; the class or &quot;include&quot; it; it just saves typing :
    • import Myproject.Mymodule.Myclasses.Myclass ;
    • Myclass mc = new Myclass ();
  • The Import Statement (continued..)
    • All of the classes of a package can be imported at one time using this form of the import statement:
    • import java.util.*;
    • This imports all of the classes in the java.util package.
  • Reserved Words
    • Reserved words or keywords are words that have a specific meaning to the compiler and cannot be used for other purposes in the program.
    • For example, when the compiler sees the word class , it understands that the word after class is the name for the class. Other reserved words are public , static , and void .
  • Reserved Words..
    • abstract default goto null synchronized
    • boolean do if package this
    • break double implements private throw
    • byte else import protected throws
    • case extends instanceof public transient
    • catch false int return true
    • char final interface short try
    • class finally long static void
    • const float native super volatile
    • continue for new switch while
  • Statements
    • A statement represents an action or a sequence of actions.
    • The statement System.out.println(&quot;Welcome to Java!&quot;) is used to display the greeting &quot;Welcome to Java!&quot;
    • Every statement in Java ends with a semicolon (;).
  • Blocks
    • A pair of braces in a program forms a block that groups components of a program.
  • Classes
    • The class is the essential Java construct.
    • A class is a template or blueprint for objects.
    • To program in Java, you must understand classes and be able to write and use them.
    • For now, though, understand that a program is defined by using one or more classes.
  • What is a class?
    • Early languages had only arrays
      • all elements had to be of the same type
    • Then languages introduced structures (called records , or structs )
      • allowed different data types to be grouped
    • Then Abstract Data Types (ADTs) became popular
      • - grouped operations along with the data
  • So, what is a class?
    • A class consists of
      • - a collection of fields , or variables , very much like the named fields of a struct
      • - all the operations (called methods ) that can be performed on those fields
      • - can be instantiated
    • A class describes objects and operations defined on those objects
  • The class hierarchy
    • Classes are arranged in a hierarchy
    • The root, or topmost, class is Object
    • Every class but Object has at least one superclass
    • A class may have subclasses
    • Each class inherits all the fields and methods of its (possibly numerous) superclasses
  • UML Representation of A Class Class name Field values Class name Method signatures : name, argument types, result type Field signatures : type and name
  • An example of a class
    • class Person { String name; int age;
    • void birthday ( ) { age++; System.out.println (name + ' is now ' + age); } }
    • class Driver extends Person { long driversLicenseNumber; Date expirationDate; }
    Variable Method
  • Creating and using an object
    • Person john; john = new Person ( ); john.name = &quot;John Smith&quot;; john.age = 37;
    • Person mary = new Person ( ); mary.name = &quot;Mary Brown&quot;; mary.age = 33; mary.birthday ( );
  • Scope of Objects
    • Java objects don’t have the same lifetimes as primitives.
    • When you create a Java object using new , it hangs around past the end of the scope.
    • Here, the scope of name s is delimited by the {}s but the String object hangs around until GC’d
      • {
      • String s = new String(&quot;a string&quot;);
      • } /* end of scope */
  • Methods
    • Method is : for eg System.out.println(“ Welcome to Java!&quot; ):
    • A collection of statements that performs a sequence of operations to display a message on the console.
    • It can be used even without fully understanding the details of how it works.
    • It is used by invoking a statement with a string argument.
    • The string argument is enclosed within parentheses. In this case, the argument is &quot;Welcome to Java!&quot; You can call the same println method with a different argument to print a different message.
  • main Method
    • The main method provides the control of program flow. The Java interpreter executes the application by invoking the main method.
    •  
    • The main method looks like this:
    •  
    • public static void main(String[] args) {
    • // Statements;
    • }
  • Static Members
    • In some cases, certain members should only belong to the class, and not be part of any object created from the class.
    • An example of such a situation is when a class wants to keep track of how many objects of the class have been created.
    • Defining a counter as an instance variable in the class definition for tracking the number of objects created, does not solve the problem.
    • Each object created will have its own counter field. Which counter should then be updated?
  • Static Members
    • The solution is to declare the counter field as being static. Such a field is called a static variable.
    • It belongs to the class, and not to any object of the class. A static variable is initialized when the class is loaded at runtime.
  • Static Members
    • Similarly, a class can have static methods that belong only to the class, and not to any objects of the class.
    • Static variables and static methods are collectively known as static members, and are distinguished from instance members in a class definition by the keyword static in their declaration.
  • Some Java OO Terminology
    • Class - collection of data (attributes) and methods that operate on that data
    • Member - either an attribute or a method of a class
    • Public Member - member which is accessible by any method in any class
    • Private Member - member which is accessible only by methods defined within the class
    • Public Class - class that is visible everywhere and can be used by any method in any class
    • Object - instance of a class
    • Object Instantiation - the creation of a new object
  • Some Java OO Terminology (Continued..)
    • Constructor - method which performs object initialization ( not creation!)
    • Object Reference - variable that holds a reference to (really the memory address of) an object
    • Instance Variable - attribute for which each object (instance) has its own copy
    • Class Variable - attribute for which there is only one copy for the class. Each object (instance) shares this copy. Also called a static variable
  • Some Java OO Terminology (Continued..)
    • Instance Method - method which operates on the attributes of an object (instance)
    • Class Method - method which does not operate on a particular object, but performs some utility function or operates on static variables. Also called a static method .
    • Method Signature - the number, type and order of arguments of a method
    • Method Overloading - defining a method with the same name but different signature as another method in the same class
  • Visibility Modifiers
    • We've already seen that a class member can be modified with the
    • public, private or protected keywords
    • If none of these modifiers are used, the member has the default visibility or &quot;package&quot; visibility
    • A package member is only accessible from within the class that defines it or a class in the same package
  • Visibility Modifiers (continued..)
    • The definitive chart!
    No No No Yes Non-subclass in different package No No Yes Yes Subclass in different package No Yes Yes Yes Class in same package Yes Yes Yes Yes Same class private package protected public MEMBER VISIBILITY ACCESSIBLE TO
  •  
  • Data Types
    • Primitive Types
    • Type Representation Range
    • byte 8-bit, signed -128 to 127
    • short 16-bit, signed -32768 to 32767
    • int 32-bit, signed -2147483648 to 2147483647
    • long 64-bit, signed -9223372036854775808 to 9223372036854775807
    • char 16-bit, unsigned, Unicode
    • float 32-bit 1.40239846e-45 to 3.40282347e+38
    • double 64-bit 4.94065645841246544e-324 to 1.79769313486231570e+308
    • boolean
  • Java Operators
    • Precedence Operator Description
    • 1 ++, -- Increment and decrement
    • 1 +, - Unary plus and minus
    • 1 ~ Bitwise complement
    • 1 ! Boolean
    • 2 *, /, % Multiplication, division, remainder
    • 3 +, - Addition and subtraction
    • 3 + String
    • 4 << Left shift
    • 4 >> Right shift with sign extension
    • 4 >>> Right shift with no extension
  • Java Operators (continued..)
    • Precedence Operator Description
    • 5 <, <=, >, >= Numeric comparison
    • 5 instanceof Type comparison
    • 6 ==, != Equality and inequality of value
    • 6 ==, != Equality and inequality of reference
    • 7 & Bitwise AND
    • 8 ^ Bitwise XOR
    • 9 | Bitwise OR
    • 10 && Conditional AND
    • 11 || Conditional OR
    • 12 ?: Conditional ternary operator
    • 13 = *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |= Assignment
  • Java Literals
    • Integer literals
    • Integer literals can be specified in octal (base 8), decimal (base10), or hexadecimal (base 16).
    • int i = 1230;
    • int i = 01230; // i = 664 decimal
    • int i = 0xFFFF;
    • Floating-point literals
    • Floating-point literals are of type double unless they are suffixed with an f denoting that they are to be produced as a float value:
    • double d = 8.31;
    • double e = 3.00e+8;
    • float f = 8.31F; float g = 3.00e+8F;
  • Java Literals (continued..)
    • Character literals
    • A literal character value can be specified either as a single-quoted character or as an escaped ASCII or Unicode sequence:
    • char a = 'a';
    • char newline = ' ';
    • char ch = 88 ; //code for X
    • Boolean Literals
    • It can have only one of two possible values, true or false
    • boolean b = false;
  • Wrapper Classes for Primitive Types
    • Sometimes we need to process primitive-type data as objects
    • Java provides a set of classes called wrapper classes whose objects contain primitive-type values:
    • Float , Double , Integer , Boolean , Character , etc.
  • Naming conventions
    • Java is case-sensitive; maxval, maxVal, and MaxVal are three different names
    • Class names begin with a capital letter
    • All other names begin with a lowercase letter
    • Subsequent words are capitalized: theBigOne
    • Underscores are not used in names
    • These are very strong conventions!
  • Type Conversion and Casting
    • When one type of data is assigned to another type of variable, an automatic type conversion will take place if
        • The two types are compatible
        • The destination type is larger than the source type.
        • Casting Incompatible Types
        • To create a conversion between two incompatible types, you must use a cast.
      • (target-type) value;
  • Type Conversion and Casting (Continued..)
    • Casting
    • int a;
    • a = 10;
    • byte b;
    • b = (byte) a;
    • byte b;
      • int i = 257;
      • b = (byte) i; // 1
    • double d = 223.22;
    • int i = (int) d; // 223
  • Automatic Type Promotion in Expressions
    • Java automatically promotes each byte type or short operand to int when evaluating an expression.
    • byte b= 50;
    • b = b * 2; // Error. Cannot assign an int to a byte
    • b = (byte) (b*2); // valid
  • Array Creation and Initialization
    • As in C, array indices start with zero
    • After creation, the array elements are initialized to the default values for their type.
    • For numeric types, this means the elements are initially zero:
    • int [] grades = new int [30];
    • grades[0] = 99;
    • grades[1] = 72;
    • Java supports the C-style curly braces {} construct for creating an array and initializing its elements when it is declared:
    • int [] primes = { 1, 2, 3, 5, 7, 7+4 };
    • An array object of the proper type and length is implicitly created.
  • An array is an object
    • Person mary = new Person ( );
    • int myArray[ ] = new int[5];
      • or
    • int myArray[ ] = {1, 4, 9, 16, 25};
    • String languages [ ] = {&quot;Prolog&quot;, &quot;Java&quot;};
    • Since arrays are objects they are allocated dynamically
    • Arrays, like all objects, are subject to garbage collection when no more references remain
      • - so fewer memory leaks
      • - Java doesn’t have pointers!
  • Array (continued..)
    • The elements are indexes and are referenced using the form arrayvar[subscript]
  • Java Control Statements
    • A group of statements executed in order is written
      • { stmt1; stmt2; ...; stmtN; }
    • The statements execute in the order 1, 2, ..., N
    • Control statements alter this sequential flow of execution
  • Java Control Statements (continued..)
  • Java Control Statements (continued..)
  • THANK YOU