Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Ingeniería de Sistemas ertificación en AVA.

Slides:



Advertisements
Similar presentations
Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
Advertisements

George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Static Keyword. What is static The static keyword is used when a member variable of a class has to be shared between all the instances of the class. All.
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
JAVA BASICS Prepared by The Smartpath Information Systems
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
OOP: Encapsulation,Abstraction & Polymorphism. What is Encapsulation Described as a protective barrier that prevents the code and data being randomly.
Programming in Java CSCI-2220 Object Oriented Programming.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
Chapter 5 Introduction to Defining Classes
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
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,
Interfaces and Inner Classes
Access Modifiers Control which classes use a feature Only class-level variables may be controlled by access modifiers Modifiers 1. public 2. protected.
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.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
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.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Basic Syntax อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 2.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
BY:- TOPS Technologies
JAVA ACCESS MODIFIERS. Access Modifiers Access modifiers control which classes may use a feature. A classes features are: - The class itself - Its member.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
External Scope CECS 277 Mimi Opkins.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
JAVA MULTIPLE CHOICE QUESTION.
Objects as a programming concept
Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Internet and Java Foundations, Programming and Practice
Chapter 3: Using Methods, Classes, and Objects
ATS Application Programming: Java Programming
Chapter 9 Inheritance and Polymorphism
null, true, and false are also reserved.
Java Programming Language
Packages and Interfaces
Interfaces.
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
Classes and Objects.
Object Oriented Programming in java
Presentation transcript:

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Ingeniería de Sistemas ertificación en AVA

3. MODIFIERS  Objectives  Modifiers  Other Modifiers

Objectives Declare classes, inner classes, methods, instance variables, static variables and automatic (method local) variables, making appropriate use of all permitted modifiers (such as public, final, static, abstract, and so forth). State the significance of each of these modifiers both singly and in combination, and state the effect of package relationships on declared items qualified by these modifiers.

Modifiers Specify that a particular feature is static, final or transientSpecify that a particular feature is static, final or transient feature: a class, a method, or a variable A group of modifiers (access modifiers) dictate which classes are allowed to use a featureA group of modifiers (access modifiers) dictate which classes are allowed to use a feature Other modifiers can be used in combination to describe the attributes of a featureOther modifiers can be used in combination to describe the attributes of a feature Keywords that give the compiler information about the nature of code, data or classes.

class Parser{... } public class EightDimensionalComplex{... } private int i; Graphics offScreenGC; protected double getChiSquared() {... } private class Horse {... } Some Legal declarations

public protected int x; // at most 1 //access modifier allowed friendly Button getBtn() {...} // friendly is not a // modifier Illegal declarations

 The most generous access modifier  A public class, variable, or method may be used in any java program without restriction  An applet is declared as a public class so that it may be instantiated by browsers  An application declares its main() method to be public so that main() may be invoked from any Java runtime environment public

 The least generous access modifier  Top-level classes may not be declared private  A private variable may only be used by an instance of the class the class that declares the variable or method private

1.class Complex{ 2.private double real, imaginary; 3.public Complex( double r, double i) { 4.real=r; imaginary=i; } 5.public Complex add(Complex c) { 6.return new Complex(real + c.real, 7. imaginary+ c.imaginary); 8. } 9.} class Client { 12. void useThem() { 13. Complex c1 =new Complex(1, 2); 14. Complex c2 =new Complex(3, 4); 15. Complex c3 =c1.add(c2); 16. double d=c3.real; // Illegal! 17. } 18.}

 Private data is hidden from every object other than the one that owns the data  If class Complex has a subclass called SubComplex, then every instance of SubComplex will inherit its own real and imaginary variables; an instance of a subclass is denied access

1.class Complex{ 2.private double real, imaginary; 3.public Complex add(Complex c) { 4.return new Complex(real + c.real, 1.imaginary + c.imaginary); 5. } 6.} 7.class SubComplex extends Complex { 8.SubComplex(double r, double i) { 9.real = r;// compiler error 10.} 11.}

 Is the name of the default access of classes, variables and methods  A class’ data and methods may be friendly as the class itself  A class’ friendly features are accessible to any class in the same  Friendly is not a java keyword  Java considers that all classes in the directory actually make up a package friendly

package class Class

protected Only variables, methods, and inner classes may be declared protected  protected features are even more accessible than friendly features  A protected feature is available to all classes in the same package, just like a friendly feature  A protected feature is available to all the subclasses of the class that owns the protected feature  This access is provided even to subclasses that reside in a different package from the class that owns the protected feature

package sportinggoods; class Ski { void applywax() {... } } package sportinggoods; class DownhillSki extends Ski { void tuneup() { applywax(); // other tuneup functionality here }}

package adifferentpackage; // class Ski now in a // different package class Ski { protected void applymax() {... } } package sportinggoods; class DownhillSki extends Ski { void tuneup() { applywax(); // other tuneup functionality here }}

Methods may not be overridden to be more private Subclasses and Method privacy A method with some particular access type may be overriden by a method with a different access type, provided there is a path from the original type to the new type. A method with some particular access type may be overriden by a method with a different access type, provided there is a path from the original type to the new type. public protected friendly private

Illegal access types for subclasses private protected friendly public

Java does not care about order of appearance of modifiers: Java does not care about order of appearance of modifiers: public final same as final public protected static same as static protected Other Modifiers Not every modifier can be applied to every kind of feature. Not every modifier can be applied to every kind of feature.

Error: “Can’t subclass final classes” class SubMath extends java.lang.Math  Applies to classes, methods, and variables  Final features may not be changed  A final class may not be subclassed  A final variable may not be modified once it has been assigned a value  If a final variable is a reference to an object, it is the reference that must stay the same, not the object final

1. class Walrus { 2.int weight; 3.Walrus(int w) { weight = w; } 4. } class Tester { 7.final Walrus w1=new Walrus(1500); 8.void test() { 9. w1=new walrus(1400); // Illegal 10. w1.weight=1800; // Legal 11.} 12. }  You may not change a final object reference  You may change data owned by an object that is referred to by a final object reference variable

1. class Mammal { 2.final void getAround() { } 3.} 4.class Dolphin extends Mammal { 5. void getAround() { } 6.} A final method may not be overriden Compiler error: “Final methods can’t be overriden”

 Can be applied to classes and methods  A class that is abstract may not be instantiated  Abstract classes defer implementation to subclasses  If a class contains one or more abstract methods the compiler insists that the class must be declared abstract abstract

abstract void travel() class Animal void travel() class Bird void travel() class Fish void travel() class Snake

The compiler insists that the class must be declared abstract if any of the following is true  The class has one or more abstract methods  The class inherits one or more abstract methods for which it does not provide implementations  The class declares that it implements an interface but does not provide implementation for every method of that interface In a way, abstract is the opposite of final: A final class MAY NOT be subclassed An abstract class MUST be subclassed

class Ecstatic { static int x=0; Ecstatic() { x++; } Ecstatic() { x++; }}  Applies to variables, methods, and even a strange kind of code that is not part of a method  You can think of a static features as belonging to a class, rather than being associated with an individual instance of the class static

Bad form Ecstatic e1 = new Ecstatic(); Ecstatic e2 = new Ecstatic(); e1.x = 100; e2.x = 200; reallyImportantVariable=e1.x; 1. Via a reference to any instance of the class: Two ways to reference a static variable

Ecstatic e1 = new Ecstatic(); Ecstatic e2 = new Ecstatic(); Ecstatic.x = 100; // why did I do this? Ecstatic.x = 200; reallyImportantVariable=Ecstatic.x; 2. Via the class name:

class SomeClass { static int i=48; int j=1; public static void main(String args[]) { i += 100; j *= 5; // compiler error }} Static methods are not allowed to use the non-static features of their class. Static methods are not concerned with individual instances of a class. They may be invoked before even a single instance of the class is constructed.

class Xyz { int w; void bumpW() { w++;}} Non-static methods have an implicit variable named this, which is a reference to the object executing the method Abbreviation for this.w++;

1.import java.awt.*; 2.public class MyFrame extends Frame { 3.Myframe() { 4.setSize(300, 300); 5.} public static void main( String args ) { 7.public static void main( String [] args ) { 8.MyFrame theFrame=new Myframe(); 9.theFrame.setVisible(true); 10.} 11.} If a static method needs to access a non-static variable or call a non-static method, it must specify which instance of its class owns teh variable or executes the method have an implicit variable named this, which is a reference to the object executing the method

class Cattle { static void foo() { } } class Sheep extends Cattle { void foo() { } } A static method may not be overrriden to be non-static (and vice-versa) Error: “Static methods can’t be overrriden”

 A static method may only access the static data of its class; it may not access non-static data  A static method may only call the static methods of its class; it may not call non-static methods  A static method has no this reference  A static method may not be overriden to be non- static Summary (static)

 It is legal for a class to contain static code that does not exist within a method body  A class may have a block of initializer code that is simply surrounded by curly braces and labeled static Static initializers public class StaticDemo { static int i=5; static { System.out.println(“Static code: i= “+ i++ ); } public static void main( String [] args ) { System.out.println(“main: i= “+ i++ ); }}

 the code inside the curlies is executed exactly once at the time the class is loaded  At class-load time, all static initialization and all free-floating static code are executed in order of appearance within the class definition Static initializer code public class StaticDemo { static int i=5; static { System.out.println(“Static code: i= “+ i++ ); } public static void main( String[] args ) { System.out.println(“main: i= “+ i++ ); }}

 Can refer only to methods  Indicates that the body of a method is to be found elsewhere  In the case of abstact methods, the body is in a subclass  With native methods, the body lies entirely outside the Java Virtual Machine (JVM), in a library  Native code is written in a non-java language, and compiled for a single target machine type  When a native method is invoked, the libarry that contains the native code ought ot be loaded and available to the JVM native

1.class NativeExample { 2.native void doSomethingLocal(int i); 3.static { 4. System.loadLibrary(“MyNativeLib”); 5.} 6.} 1.nativeExample natex; 2.natex=new NativeExample(); 3.natex.doSomethingLocal(5);

1.nativeExample natex; 2.natex=new NativeExample(); 3.natex.doSomethingLocal(5);  Callers of native methods do not have to know that the method is native  The call is made the same way as if it were non-native

 Can be applied only to variables  A transient variable is not stored as part of its object´s persistent state transient

Many objects (specifically those that implement either the Serializable or Externalizable interfaces) can have their state serialized and written to some destination outside the JVM This is done by passing the object to the WriteObject() method of the ObjectOutputStream class If the stream is chained to a FileOutputStream, then the object’s state is written to a file If the stream is chained to a socket’s OutputStream, then the object’s state is written to the network In both cases the object can be reconstituted by reading it from an ObjectInputStream

1.class WealthyCustomer extends Customer implements Serializable { 2.private float $wealth; 3. private String accessCode; 4. } Once an object is written to a destination outside JVM, none of Java’s elaborate security mechanism is in effect If an instance of this class were to be written to a file or to the Internet, somebody could snoop the access code

1.class WealthyCustomer extends Customer implements Serializable { 2.private float $wealth; 3. private transient String accessCode; 4. } Now the value of accessCode will not be written out during serialization

 Control access to critical code in multithreaded programs  To be seen in chapter 7 synchronized

 Only variables may be volatile  Such variables might be modified asynchronously, so the compiler takes special precautions (multi-processor environments) volatile