34
Introduction To Classes Session 4

Introduction To Classes

  • Upload
    ronli

  • View
    27

  • Download
    0

Embed Size (px)

DESCRIPTION

Introduction To Classes. Session 4. Review. A Java program consists of a set of classes. The Java program must have a main() method from where it begins its execution. Variables defined in a class are called the instance variables. There are two types of casting: widening and narrowing. - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction To Classes

Introduction To Classes

Session 4

Page 2: Introduction To Classes

Review• A Java program consists of a set of classes.• The Java program must have a main() method

from where it begins its execution.• Variables defined in a class are called the

instance variables. • There are two types of casting: widening and

narrowing. • Variables are basic unit of storage. • Each variable has a scope and lifetime. • Arrays are used to store several items of same

data type in consecutive memory locations.

Page 3: Introduction To Classes

Review Contd…• Java provides different types of operators. They

include:▫ Arithmetic▫ Bitwise▫ Relational▫ Logical▫ Conditional▫ Assignment

• Java supports the following programming constructs:▫ if-else▫ switch▫ for▫ while▫ do-while

• The three jump statements-break,continue and return helps to transfer control to another part of the program.

Page 4: Introduction To Classes

Objectives• Explain the Java Program Structure• Design a Simple Class• Create objects• Explain the concept of methods in a class• Implement constructors• List the features of Inheritance• Differentiate between Overloading and

Overriding of methods• Identify the access specifiers and method

modifiers

Page 5: Introduction To Classes

Java Program Structure

•Environment Information•Class Declaration•Tokens:

▫Identifiers ▫Keywords / Reserve words ▫Separators ▫Literals ▫Operators

Page 6: Introduction To Classes

Class• A class defines a new data type.

• Every time an instance of a class is created, an object is created.

• The object contains its own copy of each instance variable defined by the class.

• A dot operator ( . ) is used to access these variables.

• The dot operator links the name of the object with the name of an instance variable.

Page 7: Introduction To Classes

•The simplest form for a class definition in Java isclass ClassName{constructor1constructor2. . .method1method2. . .field1field2. . .}

Page 8: Introduction To Classes

class Employee{// constructorpublic Employee(String n, double s, int year, int month, int day){name = n;salary = s;GregorianCalendar calendar = new GregorianCalendar(year, month

- 1, day);hireDay = calendar.getTime();}// a methodpublic String getName(){return name;}// more methods. . .// instance fieldsprivate String name;private double salary;private Date hireDay;}

Page 9: Introduction To Classes

Declaring Objects • When a new class is created, a new data type is

created. • Objects are declared to represent the class. • Obtaining objects of a class is a two-step process.

They are:▫ First, a variable of the class type has to be

declared. The variable does not define an object. It is a variable that can refer to an object.

▫ Second, an actual physical copy of the object must be acquired and assigned to that variable. It is done by using the new operator.

• The new operator dynamically allocates memory for an object and returns a reference to it.

• All class objects must be dynamically allocated.

Page 10: Introduction To Classes

Fields

•annotations : Annotations and annotation types are discussed in later.

•access modifiers •static•final•transient.•volatile

Page 11: Introduction To Classes

Static Fields

•Sometimes you want only one instance of a field shared by all objects of a class.

•You create such fields by declaring them static, so they are called static fields or class variables.

•When you declare a static field in a class only one copy of the field exists, no matter how many instances of the class are created.

Page 12: Introduction To Classes

public class Item {

//static field uniqueId

private static int uniqueId = 1;

private int itemId;

private String itemName;

public Item(String itemName)

{

this.itemName = itemName;

itemId = uniqueId;

uniqueId++;

}

}

Page 13: Introduction To Classes

final Fields

•We have seen final fields used to define named constants because constants don't change value. In general, a final field is used to define an immutable property of a class or object a property that doesn't change for the lifetime of the class or object.

Page 14: Introduction To Classes

Access Control• All members of a class are always available to code in the class

itself. To control access from other classes, class members have

four possible access modifiers:

• private Members declared private are accessible only in the class

itself.

• package Members declared with no access modifier are

accessible in classes in the same package, as well as in the class

itself.

• protected Members declared protected are accessible in

subclasses of the class, in classes in the same package, and in the

class itself.

• public Members declared public are accessible anywhere the

class is accessible.

Page 15: Introduction To Classes

Class Constructors

•Special methods are used to initialize member variables of the class.

•It has the same name as the Class name and does not have a return type.

•Called automatically and immediately after an object is created.

•Two types of constructors:▫Parameterized constructors▫Implicit or default constructors

Page 16: Introduction To Classes

•you combine the constructor with the new operator▫new Date()

•A constructor has the same name as the class.

•A class can have more than one constructor.

•A constructor can take zero, one, or more parameters.

•A constructor has no return value.•A constructor is always called with the

new operator.

Page 17: Introduction To Classes

Inheritance• The attributes set for a class are inherited by the sub

classes defined within the class.

• A class that is inherited from another class is called

subclass.

• The class from which another class is derived is called

superclass.

• Subclass is a specialized superclass and can access all the

instance variables and methods defined by the superclass.

• To inherit a class, one has to use the keyword extends in

the subclass.

Page 18: Introduction To Classes

•Employee, Managerclass Manager extends Employee{added methods and fields}

Page 19: Introduction To Classes

Derived Class constructors

• Has the same name as the subclass.

• Statement that calls the constructor of the superclass should

be the first statement in the constructor of a subclass.

• The keyword super issued to call the superclass constructor.

• The keyword super can also be used to refer to methods or

instance variable of the superclass.

Page 20: Introduction To Classes

Methods in Classes• A method is defined as the actual

implementation of an operation on an object.• Syntax

access_specifier modifier datatype method_name (parameter_list)

{//body of the method

} A method is always invoked relative to some

objects of its class. Within a method there is no need to specify

the object a second time.

Page 21: Introduction To Classes

Sample Usage of Methodclass Temp{

static int num = 10;public static void show(){ System.out.println(num);}public static void main(String []

arg){ Temp tobj = new Temp(); tobj.show(); Temp t1Obj = new Temp(); t1Obj.num = 20; t1Obj.show();

}}

Output

Page 22: Introduction To Classes

Methods in Classes Contd...•Methods that have a return type other

than void, return a value to the calling routine using the return statement.

•Many methods need parameters.

•Parameters allow a method to be generalized.

Page 23: Introduction To Classes

Methods Overloading•Characteristics of overloaded methods are:

▫ Defined in the same class

▫ Have the same name

▫ Have different parameter lists

• Overloaded methods are a form of compile

time polymorphism.

•Overloading lets you define a similar

operation in different ways for different data

Page 24: Introduction To Classes

Methods Overriding

• Characteristics of overridden methods are:

▫ Defined in the superclass as well as in the

subclass.

▫ Are redefined in the subclass.

• Overridden methods are a form of runtime

polymorphism.

• Overriding lets you define a similar operation

in different ways for different object types

Page 25: Introduction To Classes

Access Specifiers for Methods

Page 26: Introduction To Classes

Method Modifiers • static

• final

• abstract

• native

• synchronized

• volatile

Page 27: Introduction To Classes

Private Methods• When implementing a class, we make all data fields private

because public data are dangerous. But what about the methods?

• Sometimes, you may wish to break up the code for a computation

into separate helper methods. Typically, these helper methods

should not become part of the public interface—they may be too

close to the current implementation or require a special protocol

or calling order. Such methods are best implemented as private.

• To implement a private method in Java, simply change the public

keyword to private.

• the designers of the class can be assured that it is never used

outside the other class operations and can simply drop it. If a

method is public, you cannot simply drop it because other code

might rely on it.

Page 28: Introduction To Classes

Static methods •are methods that do not operate on

objects. For example, the pow method of the Math class is a static method. The expression

•Math.pow(x, a) computes the power x^a.•You can think of static methods as

methods that don’t have a this parameter.

Page 29: Introduction To Classes

Native methods• The Java native method is a great way to gain and merge the power of C or

C++ programming into Java. To use Java as a scientific and high

performance language, when efficient native Java compilers are not fully

implemented, use native method can boost the performance to at least the

speed of C compiled code.

• Example showing how Java native method works.

JMPI.java :

public class JMPI

{

public native int Init(String[] args);

public native int Finalize();

static {

System.loadLibrary("JMPI");

}

}

Page 30: Introduction To Classes

this

•The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts.

Page 31: Introduction To Classes

class Rectangle{  int length,breadth;  void show(int length,int breadth){    this.length=length;    this.breadth=breadth;  }  int calculate(){    return(length*breadth);  }}public class UseOfThisOperator{  public static void main(String[] args){    Rectangle rectangle=new Rectangle();    rectangle.show(5,6);    int area = rectangle.calculate();    System.out.println("The area of a Rectangle is  :  " + area);  }}

Page 32: Introduction To Classes

Nested ClassesDefining one class within another is

called ‘Nesting’.Scope of a nested class is within the

enclosing class. There are two types of nested class.

They are: Static Non-static

Inner Class is the non-static nested class.

Page 33: Introduction To Classes

Summary• Import statements are used to access the Java

packages required for the execution of the program.• A token is the smallest unit in a program. There are

five categories of tokens:▫ Identifiers▫ Keywords▫ Separators▫ Literals▫ Operators

• Class declaration only creates a template and not an actual object.

• Objects are instances of a class and have physical reality.

• Method is the actual implementation of an operation on an object.

Page 34: Introduction To Classes

Summary Contd…• Constructors are used for automatic initialization of

objects at the time of creation.• The super keyword is used for calling the superclass

constructors.• To inherit a class from the superclass, the extends

keyword is used.• Overloaded methods are a form of static polymorphism

and Overridden methods are a form of dynamic polymorphism.

• Java access specifiers: public, protected, private help in the implementation of encapsulation.

• The following modifiers are provided by Java: static, final, abstract, native, synchronized, and volatile.

• Nested class can be static or non-static.