Java Classes.

Slides:



Advertisements
Similar presentations
I NHERITANCE Chapter 10. I NHERITANCE Mechanism for enhancing existing classes You need to implement a new class You have an existing class that represents.
Advertisements

1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
Chapter 13 Inheritance. An Introduction to Inheritance Inheritance: extend classes by adding methods and fields (variables) Example: Savings account =
ITEC200 – Week03 Inheritance and Class Hierarchies.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
Road Map Introduction to object oriented programming. Classes
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
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
What is inheritance? It is the ability to create a new class from an existing class.
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.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java Class Structure. Class Structure package declaration import statements class declaration class (static) variable declarations* instance variable.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
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.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
Inheritance and Polymorphism
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
University of Central Florida COP 3330 Object Oriented Programming
Computer Science II Exam 1 Review.
Chapter 9 Inheritance and Polymorphism
Extending Classes.
Java Programming Language
Polymorphism and access control
Object Oriented Programming in java
CIS 199 Final Review.
Java Programming Language
Chapter 8 Class Inheritance and Interfaces
Chapter 11 Inheritance and Polymorphism Part 2
Classes, Objects and Methods
Chap 2. Identifiers, Keywords, and Types
Chapter 11 Inheritance and Encapsulation and Polymorphism
Review for Midterm 3.
Chapter 7 Objects and Classes
CS 240 – Advanced Programming Concepts
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Java Classes

Objects and Classes Classes are concepts, objects are instances that embody those concepts. car class objects A class captures the common properties of the objects instantiated from it. A class characterizes the common behaviors of all the objects that are its instances.

A simplified view of classes, objects, and methods A class can be considered as a user defined data type. An object is an instance of a class, i.e. a value of an user defined data type. Methods are functions/procedures that can be applied to objects, i.e. operators can be applied to data values. class ↔ user defined data type objects ↔ data values methods ↔ operators/behaviors

Java's predefined classes arrays strings vectors Hash tables wrapper classes

Classes and Source Files Each class is stored in a separate file. The name of the file must be the same as the name of the class, with the extension class. A source file must have the extension java. By convention, the name of a class (and its source file) always starts with a capital letter. public class Name { ... } Name.java (In Java, all names are case-sensitive.)

class-modifier class SomeClass { Class definition SomeClass.java import ... import statements class-modifier class SomeClass { Class header Fields/members Constructors Methods Variables that define the object’s state; can hold numbers, characters, strings, other objects Functions for constructing a new object of this class and initializing its fields } Actions that an object of this class can take (behaviors)

Using classes Declaring object variables: class name variablename; Creating objects: variable = new classname( ); Accessing variable members variable.v_member; Accessing method members: variable.method( )

Object reference The new operation instantiates an object of a particular class, and returns a reference to it. This reference is a handle to the location where the object resides in memory. var = new classname( ); The reference is stored in the variable “var." A declaration like this classname var; creates a reference variable without instantiating any object. Java uses null to represent such un-initialized reference variables. object var X=4 VS. 4

Value vs. Reference int x=1, y=1; if (x==y) … Integer I1, I2; I1 = new Integer(5); I2 = new Integer(5); if (I1==I2)…. If (I1.equals(I2))….

Value vs. Reference conti. public class primitiveVSreference { public static class Complex { double re, im; public Complex(double x, double y) { re = x; im = y; } public String toString() { String tmp = "("+re+","+im+")"; return tmp; } public static void main(String[] args) { int x = 10,; int y = x; x = 100; System.out.println("x="+x+", y="+y); Complex C1 = new Complex(1.2, 2.3); Complex C2 = C1; C1.re = 2.4; C1.im = 4.6; System.out.println("C1 = "+ C1.toString()); System.out.println("C2 = "+ C2.toString()); x 10 100 y 10 C1 1.2 2.3 C2 2.4 4.6

Method Declaration A method begins with a method header double add(int x, int y) { double sum = x + y; return sum; } A method begins with a method header The method header is followed by the method body In the method header, double is the return type, add is the method name, and the items within parentheses , i.e. x and y constitute the parameter list.

Method Declaration conti. The parameter list specifies the type and name of each parameter The return type indicates the type of value that the methods sends back to the calling location A method that does not return a value has a void return type The return statement specifies the value to be returned Its expression must conform to the return type

Passing Parameters to Methods When a method invocation is made, any actual parameters included in the invocation are passed to the method All parameters are passed by value. ie, a copy is made. The value of fundamental data types are copied. The value of object references (ie memory addresses) are copied Parameters become local variables within the method.

Primitive VS Reference parameters public class primitiveVSreference2 { public static class Complex { double re, im; public Complex(double x, double y) { re = x; im = y; } public String toString() { String tmp = "("+re+","+im+")"; return tmp; } static void add1(int x) { x++; }; static void Add1(Complex C) { C.re ++; C.im++; } public static void main(String[] args) { int x = 10; add1(x); System.out.println("x="+x); Complex C = new Complex(1.2, 2.3); Add1(C); System.out.println("C = "+ C.toString());

A subclass is A superclass class classname extends parent-class { [variable declaration;] [method declaration;] } Deriving Classes Superclass (Base/parent class) subclass extends superclass A subclass is A superclass Subclass (Derived class) Inheritance is used to model the Is-A relationship. Inheritance- inherits fields and methods of its superclass. Advantage of inheritance: Code reuse Overriding methods - redefine methods of the superclass. Overloading methods – more than one method with the same name (but with different parameters) in a class.

Inheritance Example public class Student { int student_id; int year; String name; public Student(String nm, int id, int y) { name = new String(nm); student_id = id; year = y; } ….. }

Inheritance example conti. public class GradStudent extends Student { String dept; String thesis; // constructor public GradStudent(String nm, int id, int y, String d, String th) { super(nm, id, y); // call superclass constructor /* Or name = new String(nm); student_id = id; year = y; */ dept = new String(d); thesis = new String(th); }

Inheritance example conti. public class inheritanceTest { public static void main(String[] args) { Student S = new Student(“John”, 1234, 3); GradStudent GS = new GradStudent(“Tom”, 1111, 2, "csC", "Algorithm"); S.student_id = 3690; GS.student_id = 2468; …. }

class Y extends X { ….. } X x = new X(); Y y = new Y(); x = y; ok? More general (superclasses) class X class Y X Y Y X Y X X X More specialized (subclasses) X x = new X(); Y y = new Y(); x = y; ok? y = x; ok?

instanceof instanceof is a keyword that tells you whether a variable “is a” member of a class Example X x; if (x instanceof Y) ….

Java casting A narrowing conversion requires an explicit typecast E.g. y = (Y) x; The narrowing conversion produces a runtime error if x does not contain to a Y object The compiler takes the programmer’s word for the validity of the explicit typecast The virtual machine checks the validity at the run time

Method Overriding Overriding refers to the introduction of a method in a subclass that has the same signature, i.e. the same name, parameter types, and return type of a method declared in the superclass. Consequently, the method in the subclass replaces the method in the superclass. Example public class T { public void f(int x) { … } } public class S extends T { public void f(int y) { … } T t = new T(); S s = new S(); t.f(); // invoke f of class T s.f(); // invoke f of class S

Method Overloading Overloading is reusing the same method name with different argument types and perhaps a different return type. Methods with overloading names are effectively independent methods. overloaded methods can call one another simply by providing a normal method call with an appropriately formed argument list. Constructors can also be overloaded after all they are also methods. public class Date { private int year, month, day; Date() { year = month = day = 0; } public Date(int y, int m, int d) { year = y; month = m; day = d; public class program { public static void main(String[] args) { Date D1 = new Date(); Date D2 = new Date(2002, 7, 20); ... }

Instance Fields Can’t override fields Can: Inherit a field: All fields from the superclass are automatically inherited Add a field: Supply a new field that doesn’t exist in the superclass What if you define a new field with the same name as a superclass field? Each object would have two instance fields of the same name Fields can hold different values Legal but extremely dangerous.

Common Error: Shadowing Fields public class CheckingAccount extends BankAccount { private double balance; // Shadowing public void deposit(double amount) { transactionCount++; balance = balance + amount; } } BankAccount portion CheckingAccount balance transactionCount 1000 2 3000

Invoking Super class Methods/Fields class A { public void printName() { int x=1; System.out.println( "Method A" ); } class B extends A{ int x=2; System.out.println( "Method B" ); … printName(); x = 3; super.printName(); super.x = 4;

Access Control Access control is a way to limit the availability of the code to other entities of the program. Class modifiers: Public: allows the class to be accessed by any object from any package. Final: prevents a class from being subclassed. Abstract: forces the class to be extended, so that it cannot be instantiated. Access modifiers: public private protected default is public within a package. The static modifier: means the method/field is shared by all objects in the class. The synchronized modifier (for multi threads) The native modifier: (Code in machine code.)

Access Modifier package … int w; public int x; protected int y; private Z;

Access Control Summary Modifier Class Method Variable final Y abstract N static native transient volatile Synchronized Access Control Summary visibility Accessible to Public Protected Default Private same class Y class in same package/directory N subclass in different package Non subclass in different package

Object: The Cosmic Superclass The Object class is the highest super class (ie. root class) of Java. All classes defined without an explicit extends clause automatically extend Object . Most useful methods: String toString() boolean equals(Object otherObject) Object clone() // Create copies Good idea to override these methods in your classes

Packages - Grouping related classes Declaring packages. package myPackage; class MyClass { ... } Import packages import myPackage.MyClass; A package must be in a directory with the same name as the package. Moreover, the directory must be listed in the environment variable CLASSPATH or be a subdirectory of the current directory.

Package declaration & order package name import statements public/non public classes main method - Signature of the main() method can be any of these: public static void main(String args[] ) public static void main (String [] args ) static public void main (String [] args)

Wapper classes Type wrappers are classes used to enclose a simple value of a primitive type into an object. Integer Long Boolean Character Double Float Notes: All wrapper objects are immutable. Once created the contained value can't be changed. Wrapper classes are final and can't be subclassed

Using wrapper classes Autoboxing & Unboxing Boxing: Wrap a value of a primitive type into a wrapper class, e.g. Chacter C = new Character('x'); Unboxing: Extract a value of a primitive type from a wrapper class, e.g. char c = C.charValue(); Autoboxing & Unboxing For Java 1.5 or later, these are legal: Integer X = 5; //5 is boxed automatically. Integer Y = 2*X + 3; //X is unboxed & 13 is boxed automatically. Note: Boxing and unboxing cost CPU time and memory space.

Inner classes Most classes we have seen are “top level” classes. It is possible (and useful) to define a class inside another class. An inner class or nested class is a class declared entirely within the body of another class or interface. Every class compiles to a separate .class file Inner classes compile to files with a $ in their names Inner classes were not in Java 1.0

Member classes A member class is a class that is declared as a non-static member of a containing class. class Outer { int n; class Inner { int m; void setN(int x) { n = x; } } void f ( ) { new Inner( ).setN(5); Compiled to Outer$Inner.class file. Inner has the access to outer’s variable n

Scope rules of identifiers An identifier defined in a block is known in the entire block except in those subordinate blocks in which the identifier is redefined. class outer { int x = 0, y = 0, z=0; class inner {int x = 10; void f ( ) { int y = 100; System.out.printf(“x=%d, y=%d, z=%d\n”, x, y, z); } …..

A scope implication An identifier can't be declared twice in it’s scope. for (int i = 1; i <= 100 * line; i++) { int i = 2; // ERROR System.out.print("/"); }

Scope rules are static public class scope { static int x = 1; static void f() { System.out.println(“x=“+x); } public static void main(String[] args) { int x = 10; f();

Homework In what classes can w be accessed? package P; public class A { int w; public int x; protected int y; private int z; } package P; public class B{ } import P.*; public class E{ } import P.*; class F extends E{ } import P.*; class D extends B{ } import P.*; class C extends A{ } In what classes can w be accessed? In what classes can x be accessed? In what classes can y be accessed? In what classes can z be accessed?