Defining a ClasstMyn1 Defining a Class A class is a template that defines the form of an object. It specifies both the data and the code that will operate.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Chapter 3 Introduction to Classes, Objects, Methods, and Strings
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Road Map Introduction to object oriented programming. Classes
Lecture 2 Classes and objects, Constructors, Arrays and vectors.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
VBA Modules, Functions, Variables, and Constants
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Abstract Data Types and Encapsulation Concepts
Introduction to Java Java SE 8 for Programmers Paul Deitel Harvey Deitel Deitel Developer Series 2014.
Chapter 6: A First Look at Classes
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
A First Look At Classes Chapter 6. Procedural Programming In procedural- programming all the program functionality is written in a few modules of code.
1.  A method describes the internal mechanisms that actually perform its tasks  A class is used to house (among other things) a method ◦ A class that.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
4.1 Instance Variables, Constructors, and Methods.
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.
Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
Classes Definition A class is a data type whose variables are objects Object – a variable that has member functions as well the ability to hold.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
Lecture 08. Since all Java program activity occurs within a class, we have been using classes since the start of this lecture series. A class is a template.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Topics Instance variables, set and get methods Encapsulation
Class Fundamentals BCIS 3680 Enterprise Programming.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Topic: Classes and Objects
Static data members Constructors and Destructors
Introduction to Classes and Objects
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Yanal Alahmad Java Workshop Yanal Alahmad
Chapter 3: Using Methods, Classes, and Objects
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Object Oriented Programming in java
Classes and Objects.
7 Arrays.
Lecture 5- Classes, Objects and Methods
Object Oriented Programming in java
Java Programming Language
Presentation transcript:

Defining a ClasstMyn1 Defining a Class A class is a template that defines the form of an object. It specifies both the data and the code that will operate on that data. Java uses a class specification to construct objects. Objects are instances of a class. Thus, a class is essentially a set of plans that specify how to build an object.

Defining a ClasstMyn2 When you define a class, you declare its exact form and nature. You do this by specifying the instance variables that it contains and the methods that operate on them. Although very simple classes might contain only methods or only instance variables, most real-world classes contain both. A class is created by using the keyword class :

Defining a ClasstMyn3 class classname { //declare instance variables type var1; type var2; //… //declare methods type method1(parameters) { //body of method } type method2(parameters) { //body of method } //… }

Defining a ClasstMyn4 A well-designed class should define one and only one logical entity. For example, a class that stores names and telephone numbers will not normally also store information about the stock market, average rainfall, sunspot cycles, or other unrelated information. The point here is that well-designed class groups logically connected information. Our first class does not have any instance variables but only one method, displayMessage() :

Defining a ClasstMyn5 package TimoSoft; public class GradeBook { public void displayMessage() { System.out.println("Welcome to the GradeBook!"); }

Defining a ClasstMyn6 Methods are subroutines that usually manipulate the data defined by the class and, in many cases, provide access to that data. In most cases, other parts of your program will interact with a class through its methods. Usually each method performs only one task. The general form of a method is: return-type name(parameter-list) { //body of method }

Defining a ClasstMyn7 The type of data returned by the method can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. The parameter list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. To add a method to a class you just specify it within class’s declaration.

Defining a ClasstMyn8 Next we have to write the main() method to test our first class:

Defining a ClasstMyn9 package TimoSoft; public class GradeBookTest { public static void main(String[] args) { GradeBook myGradeBook=new GradeBook(); myGradeBook.displayMessage(); } run: Welcome to the GradeBook! BUILD SUCCESSFUL (total time: 2 seconds)

Defining a ClasstMyn10 In the preceding program, the following line was used to declare an object of type GradeBook: GradeBook myGradeBook=new GradeBook(); This declaration performs two functions. First, it declares a variable called myGradeBook of the class type GradeBook. This variable does not define an object. Instead, it is simply a reference variable that can refer to an object of type GradeBook.

Defining a ClasstMyn11 Second, the declaration creates a physical copy of the object and assigns to myGradeBook a reference to that object. This is done by using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. This reference is then stored in a variable myGradeBook. Thus, in Java, all class objects must be dynamically allocated.

Defining a ClasstMyn12 The class name followed by parentheses specifies the constructor for the class. If a class does not define its own constructor (like in the previous example), new will use the default constructor supplied by Java. Since memory is finite, it is theoretically possible that new will not be able to allocate memory for an object because insufficient memory exists. If this happens, a run-time exception will occur.

Defining a ClasstMyn13 The two steps combined in the preceding statement can be rewritten like this to show each step individually: GradeBook myGradeBook; myGradeBook=new GradeBook (); The first line declares myGradeBook as a reference variable to an object of type GradeBook. Thus, myGradeBook is a variable that can refer to an object, but it is not an object, itself. At this point, myGradeBook contains the value null, which means that it does not refer to an object.

Defining a ClasstMyn14 The next line creates a new GradeBook object and assigns a reference to it to myGradeBook. Now, myGradeBook is linked with an object. For example, consider the following fragment: Vehicle car1=new Vehicle(); Vehicle car2=car1; Interpretation: reference variables car1 and car2 will both refer to the same physical object. To explain it some other way: reference variables car1 and car2 does both have the same address content.

Defining a ClasstMyn15 In the preceding example we used the dot operator. The dot operator links the name of an object with the name of a member.

Defining a ClasstMyn16 Now that the very fundamentals of classes has been covered, we can take an example where we read integers from the keyboard using the class Scanner :

Defining a ClasstMyn17 package addthem; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input=new Scanner(System.in); int number1, number2, sum; System.out.print("Enter first integer: "); number1=input.nextInt(); System.out.print("Enter second integer: "); number2=input.nextInt(); sum=number1+number2; System.out.printf("Sum is %d\n", sum); }

Defining a ClasstMyn18 run: Enter first integer: 5 Enter second integer: 9 Sum is 14 BUILD SUCCESSFUL (total time: 20 seconds)

Defining a ClasstMyn19 At the beginning from the previous example: Scanner input=new Scanner(System.in); This expression creates a Scanner object that reads data typed by the user at the keyboard. At the very beginning there was the line import java.util.Scanner; That means that the program uses class Scanner.

Defining a ClasstMyn20 Why do we need to import class Scanner, but not for example class System ? Most classes you will use in Java programs must be imported. For example classes System, Number and Math are in package java.lang, which is implicitly imported into every Java program. Thus, all programs can use package java.lang’s classes without explicitly importing them.

Defining a ClasstMyn21 Actually, the import declaration is not required if we always refer to class Scanner as java.util.Scanner, which includes the full package name and class name. This is known as the class’s fully qualified class name.

Defining a ClasstMyn22 The last statement was: System.out.printf("Sum is %d\n", sum); The f in the name printf stands for formatted. The format specifier %d is a placeholder for an int value (in this case the value of sum) – the letter d stands for decimal integer.

Defining a ClasstMyn23 A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type. Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object. All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero:

Defining a ClasstMyn24 package TimoSoft; public class Rectangle { double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a ClasstMyn25 package TimoSoft; public class RectangleTest { public static void main(String[] args) { Rectangle first=new Rectangle(); first.getWidth(); first.getHeight(); } run: The width is 0.0 The height is 0.0 BUILD SUCCESSFUL (total time: 0 seconds)

Defining a ClasstMyn26 However, once you define your own constructor, the default constructor is no longer used. Now we add the constructor which initializes the instance variables:

Defining a ClasstMyn27 package TimoSoft; public class Rectangle { double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a ClasstMyn28 void setWidth(double w) { width=w; } void setHeight(double h) { height=h; } Rectangle(double wVal, double hVal) { setWidth(wVal); setHeight(hVal); }

Defining a ClasstMyn29 package TimoSoft; public class RectangleTest { public static void main(String[] args) { Rectangle first=new Rectangle(12.5, 7.9); first.getWidth(); first.getHeight(); } run: The width is 12.5 The height is 7.9 BUILD SUCCESSFUL (total time: 0 seconds)

Defining a ClasstMyn30 Each object of the class will have its own copy of each of the non-static fields or instance variables that appear in the class definition. Each object will have its own values for each instance variable. The name instance variable originates from the fact that an object is an instance or an occurrence of a class, and the values stored in the instance variables for the object differentiate the object from others of the same class type.

Defining a ClasstMyn31 Although methods are specific to objects of a class, there is only ever one copy of each method in memory that is shared by all objects of the class, as it would be extremely expensive to replicate all instance methods for each object. A special mechanism ensures that each time you call a method the code executes in a manner that is specific to an object. Each time an instance method is called, the this variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific members of the object referred to by this.

Defining a ClasstMyn32 Parameters are added to a constructor in the same way that they are added to a method: just declare them inside the parentheses after the constructor’s name. It is possible to pass one or more values to a method when the method is called. A value passed to a method is called an argument. Inside a method, the variable that receives the argument is called a parameter. Parameters are declared inside the parentheses that follow the method’s name.

Defining a ClasstMyn33 The parameter declaration syntax is the same as that used for variables. A parameter is within the scope of its method, and aside from its special task of receiving an argument, it acts like any other local variable.

Defining a ClasstMyn34 Classes often provide methods to allow clients of the class to set (i.e., assign values to) or get (i.e., obtain the values of) instance variables. So often there are “setters” which are called by the constructor. The names of these methods need not begin with set or get, but this naming convention is highly recommended.

Defining a ClasstMyn35 The mutator method, sometimes called a "setter", is most often used in keeping with the principle of encapsulation. According to this principle, instance variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private instance variable.

Defining a ClasstMyn36 Often a "setter" is accompanied by a "getter“, also known as an accessor method, which returns the value of the private instance variable.

Defining a ClasstMyn37 Next modification: The instance variables width and height will be asked from the user:

Defining a ClasstMyn38 package TimoSoft; import java.util.Scanner; public class Rectangle { double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a ClasstMyn39 void setWidth() { Scanner input1= new Scanner(System.in); System.out.print("Enter the width: "); width=input1.nextDouble(); } void setHeight() { Scanner input2= new Scanner(System.in); System.out.print("Enter the height: "); height=input2.nextDouble(); } Rectangle() { setWidth(); setHeight(); }

Defining a ClasstMyn40 package TimoSoft; public class RectangleTest { public static void main(String[] args) { Rectangle first=new Rectangle(); first.getWidth(); first.getHeight(); }

Defining a ClasstMyn41 run: Enter the width: 34,8 Enter the height: 23,4 The width is 34.8 The height is 23.4 BUILD SUCCESSFUL (total time: 26 seconds) When entering the double value from the keyboard, the delimiter is comma!!

Defining a ClasstMyn42 If you don’t like the delimiter to be comma with the double type instance variable, you can change the localization: public static synchronized void setDefault(Locale newLocale) Sets the default locale for this instance of the Java Virtual Machine. So it would be enough to add this in one of the methods:

Defining a ClasstMyn43 package TimoSoft; import java.util.Scanner; import java.util.Locale; public class Rectangle { double width, height; void getWidth() { System.out.println("The width is "+width); } void getHeight() { System.out.println("The height is "+height); }

Defining a ClasstMyn44 void setWidth() { Locale.setDefault(Locale.ENGLISH); Scanner fromKeyboard= new Scanner(System.in); System.out.print("Enter the width: "); width=fromKeyboard.nextDouble(); } void setHeight() { Locale.setDefault(Locale.ENGLISH); Scanner fromKeyboard= new Scanner(System.in); System.out.print("Enter the height: "); height=fromKeyboard.nextDouble(); } Rectangle() { setWidth(); setHeight(); }

Defining a ClasstMyn45 package TimoSoft; public class RectangleTest { public static void main(String[] args) { Rectangle first=new Rectangle(); first.getWidth(); first.getHeight(); } run: Enter the width: 3.5 Enter the height: 78.2 The width is 3.5 The height is 78.2 BUILD SUCCESSFUL (total time: 18 seconds)

Defining a ClasstMyn46 In Java objects are always allocated dynamically from a pool of free memory by using the new operator. Memory is not infinite, and the free memory can be exhausted. A key component of any dynamic allocation scheme is the recovery of free memory from unused objects, making that memory available for subsequent reallocation. In some programming languages, the release of previously allocated memory is handled manually.

Defining a ClasstMyn47 For example, in C++, you use the delete operator to free memory that was allocated. However, Java uses a different, more trouble-free approach: garbage collection. Java’s garbage collection system reclaims objects automatically – occurring transparently, behind the scenes, without any programmer intervention. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object is released. This recycled memory can then be used for a subsequent allocation.

Defining a ClasstMyn48 Garbage collection occurs only sporadically during the execution of your program. It will not occur simply because one or more objects exist that are no longer used. For efficiency, the garbage collector will usually run only when two conditions are met: there are objects to recycle, and there is a need to recycle them. Thus, you can’t know precisely when garbage collection will take place.

Defining a ClasstMyn49 Within an instance method or a constructor, this is a reference to the current object – the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using this keyword is because a field is shadowed by a method or constructor parameter:

Defining a ClasstMyn50 package TimoSoft; public class Point { int x, y; void setXvalue(int x) { this.x=x; } void setYvalue(int y) { this.y=y; } int getXvalue() { return x; }

Defining a ClasstMyn51 int getYvalue() { return y; } Point(int x, int y) { setXvalue(x); setYvalue(y); }

Defining a ClasstMyn52 package TimoSoft; public class PointTest { public static void main(String[] args) { Point first=new Point(3, 4); System.out.println("The coordinate values are "+ first.getXvalue()+" and "+first.getYvalue()+"."); } run: The coordinate values are 3 and 4. BUILD SUCCESSFUL (total time: 0 seconds)

Defining a ClasstMyn53 In the preceding example each argument to the constructor (or actually to the methods setXvalue() and setYvalue() ) shadows one of the object’s instance variables. Inside the method setXvalue(int x) x is a local copy of the method’s argument. To refer to the Point instance variable x, the method must use this.x.