CSC435: Object-Oriented Programming - Topic 3 - Basic Class Concept PDF

Summary

These notes cover the basic concepts of classes in Java programming. The document discusses class concepts, class definitions, data members, basic method types, and predefined classes, ideal for undergraduate-level computer science students.

Full Transcript

CSC435: OBJECT ORIENTED PROGRAMMING Topic 03 – Basic Concepts of Classess Objective & Learning Outcomes Objective  To introduce students the concept of classes in Java programming language Learning Outcomes At the end of this session, students will be able to: Discuss about the concept of...

CSC435: OBJECT ORIENTED PROGRAMMING Topic 03 – Basic Concepts of Classess Objective & Learning Outcomes Objective  To introduce students the concept of classes in Java programming language Learning Outcomes At the end of this session, students will be able to: Discuss about the concept of classes in Java Programming. Write Java codes for Class and it’s content. Explain about the predefined classes and the wrapper classes. Content  Class concept  Class definition  Data members  Basic types of methods  Methods definition (Note: Cover static method only to highlight why main is static, but NOT how to construct static methods)  Static fields  Predefined classes and wrapper classes Class concept 4  In OOP, the central modules are classes where data and the method to manipulate the data are encapsulated  A Java program is composed of one or more classes  Predefined classes  User-defined classes  One of the classes in a program must be designated as the main class Class concept 5  The mechanism in Java that allows us to combine data and operations on the data in a single unit  A Java Programming language provides a wealth of pre-defined classes (API) such as:  Class String  Class Character  Class Math  Class Jframe  Can be access at : https://docs.oracle.com/javase/8/docs/api/  To design a class, you must know what data need to manipulate and what operations need to manipulate the data Class Definition 6  Class is the object definition  It acts as a template or blueprint of an object or a plan  A class definition contains  Data member (usually specified as private) ◼ Data members is the object attributes – also known as attributes, fields, or properties ◼ Data members can be any data type - primitives or objects  Methods (usually specified as public) ◼ Method represents the operation on the attributes Class Definition 7  The class definition consists of header (class name) and body  The body consisting of data and methods (behaviors)  Syntax: class className { // data members declarations class members // methods definitions }  modifier can be either public, private, or without any (default / package access)  If the class is public, it can be access by other classes  If the class is private, it is restricted to be access by others Class Definition 8  A class can contain any of the following variable types:  Instance variables (attribute)− variables defined within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.  Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.  Class variables − variables declared within a class, outside any method, with the static keyword. Template for Class Definition 9 Class Comment Import Statements class Class Name { Data Members Methods (incl. Constructor) } The Definition of the Bicycle Class 10 public class Bicycle { // Data Member (instance variable) private String ownerName; //Constructor: Initialzes the data member public Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { class members return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; } } local variable Class Diagram for Bicycle 11 Bicycle - ownerName + Bicycle( ) Modifier - private + getOwnerName( ): String + public + setOwnerName(String) :void Component of a Class (members of the 12 class)  A member of a class can be a attribute(data member) or method or an inner class  The members of a class are classified into 4 categories (modifier):  private: if a member of a class is private, you cannot access it outside the class  public: if a member of a class is public, you can access it outside the class  protected : cover in inheritance  default: if a class member is declared without any modifiers, then that class member can be accessed from anywhere in the package Members of a class (cont.) 13  Deciding which members to make private or public depends on the nature of each member  The general rule :  Any member that needs to be accessed from outside the class is declared public  Any member that should not be accessed directly by the user should be declared private Data Members  The data members of a class are also called fields  The non-static data members (variables) of a class, are called instance variables if declared without using the modifier static  Example of instance variables declaration: private int hour; private int minute; private int second; private String ownerName; Basic types of methods  Method : is a set of instructions designed to accomplish a specific task  2 types:  pre-defined/standard (already written and provided in the system) ◼ nextInt(), print(), chartAt()  user defined ◼ calculateAverage(), displayInfo()  One of the classes in Java application program must have the method called main() A simple Java Program 16  Every Java program must have at least one class  To run a class, a class must contain a main method. This class is called Java program or Java application Class header Main method Method Declaration 17 ( ){ } Modifier Return Type Method Name Parameter public void setOwnerName ( String name ) { ownerName = name; Statements } Method Declaration (cont.) 18  A modifier  defines the visibility (which methods can call the method).  Modifier ◼ public - method can be ‘called’ from any other methods in the package. ◼ static indicates that the method is unique and can be invoke without any instances/objects.  The return type  indicates the type of data which will be return by the method.  void shows that the method does not return any value.  If the return type is not void, the method must has a return statement.  The name of a method follows the rules of using identifier.  Parameters list are data which the method receives in order to complete the operation that the method need to do. Basic types of methods 19  Constructor  A special method that is executed when a new instance of the class is created (when new operator is called)  Accessor  A method that returns information about object (get method)  Mutator  A method that sets a property (data) of an object (set method)  Processor  Replace the object’s data or use the object’s data to calculate a process. May be return value to the calling object.  Printer (toString)  method to display information of the data members.  Is a method that returns a string representation of an object attributes  Use when more than one data involve Type of methods: constructors 20  Constructors characteristics:  has the same name as the class  It executes automatically when object of the class is created.  no return type hence no “return” statement  Objective : to initialize the data members and perform any other initialization tasks  Three types of constructors  defaultconstructor (Without parameters)  normal constructor (With parameters)  Copy constructors Default Constructor 21  Is automatically created by Java if you don’t define a constructor for a class public ( ){ } Modifier Class Name Parameter public Bicycle ( ) { ownerName = "Unassigned"; } Statements Normal constructors 22  A constructor that has a parameter  This constructor that receives several values from the main method through parameters and initialize the data members of an object with the given value  This method can be overloaded as long as the number of parameters and/or the type of parameters are different.  Example: public Bicycle (String ownNm ) { ownerName = ownNm; } Copy constructors 23  A constructor that initializes a new object by using the values of an existing object  It is used to copy an object into another object  The parameter of a copy constructor is an object from the same class.  Copy constructor makes a member-by-member copy from the argument to the object being created  Example: public Bicycle (Bicycle obj ) { ownerName = obj.ownerName; } Type of methods: Accessor (get method) 24  Purpose: to get (retrieve) data from the object instance  Common characteristics of an accessor:  It can have any name, but usually starts with “get….”.  It must have a return type and return keyword  It may have one or more parameters depending on the implementation of the method.  Example: //Returns the name of this bicycle's owner public String getOwnerName() { return ownerName; } Type of methods: Mutator (set method) 25  Purpose: to set/bring in data to the object instance  Common characteristics of an mutator:  It can have any name, but usually starts with “set….”.  It should not have a return type and return keyword  It must have one or more parameters depending on the implementation of the method.  Example: //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; } Type of methods: Printer (toString) 26  Purpose: to returns a string representation of an object attributes.  Common characteristics of a printer:  It can have any name, but usually name with “toString()”.  It has a return type (String) and return keyword.  Example: public String toString() { String out; out = "The owner name: "+ ownerName; return out; } Type of methods: processor 27  Purpose: to calculate or process the data members  The output of the process may replace the value of a data members or may be returned to the calling method.  Example: //This method will calculate area of square public double calcArea() { return length * width; } Creating an Object 28  A class provides the blueprints for objects.  An object is created from a class.  In Java, the new keyword is used to create new objects.  There are three steps when creating an object from a class  Declaration − A variable declaration with a variable name with an object type.  Instantiation − The 'new' keyword is used to create the object.  Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object. Creating an Object 29 public class Bicycle { private String ownerName; //Data Member //Constructor: Initializes the data member public Bicycle() { //default Constructor ownerName = "Unknown"; } public Bicycle(String name ) { //normal Constructor If we compile and run the ownerName = name; above program, then it will } produce the following result public String toString() { // printer Output String out = "The owner name: "+ownerName; return out; The owner name: Kamal } public static void main (String args[]) { Bicycle bike = new Bicycle("Kamal"); //creating object System.out.println(bike.toString()); } } Example: Implementation of constructor, 30 mutator, accessor and toString method Example: Implementation of constructor, 31 mutator, accessor and toString method Static Method 32  A method that does not operate on an object but receives all of its data as arguments.  Independent function  If the method has public modifier, it is referred as a general-purpose method which means it is constructed to be used to perform a general purpose task.  It uses the keyword static public static void main(String[] args) {...}  Static methods cannot read instance variables. Static field 33  a data member of a class is declared using the modifier static, it can be accessed by using the name of the class  Static field is also known as class field, where data shared by all instances (object) of a class  Static data belongs to the entire class not to individual object  All objects of the class share the static data public class Bicycle { private String ownerName; private String tagNo; private static int counter; } *** every Bicycle object has its own ownerName and tagNo instance fields, but there is only a single copy of the counter variable because that variable is shared by all Bicycle objects. Example of Java Class Definition public class Student { private String stuNum; Class header : modifier, reserved word class private String stuName; and class name private String stuProg; Attributes / data members/ variables private double cgpa; declaration: identify attributes of an object and its data type public Student() { Default constructor : initialize stuNum= " "; the object variables to zero or stuName = " "; null stuProg = " "; cgpa = 0.0; } Mutator method: public void setData(String s,String n,String p,double c) to set the { int num; object’s value Method definition stuNum = s; stuName = n; stuProg =p; cgpa = c; } public String toString() I/O method : to display the object’s values { return stuNum + " " + stuName + " " + stuProg + " " + cgpa; 34 } } Example of Java Application import java.io.*; Import the package: be able to use the import java.util.*; pre-defined classes public class StuApp Class header: modifier, reserved word class and class name { public static void main(String[ ] args) Main method { Create input object: to Scanner inp = new Scanner(System.in); input using I/O console To create Student std = new Student(); Student’s object System.out.println(" Enter student number "); String num = inp.next(); System.out.println(" Enter student name "); Read the input String name = inp.next(); entered by user using I/O console System.out.println(" Enter student program "); String prog = inp.next(); System.out.println(" Enter cgpa "); double cgpa = inp.nextDouble(); std.setData(num, name, prog, cgpa); To set the object’s values (properties To display the values) System.out.println(std.toString()); object’s values } 35 } Pre-defined classes 36 Usage Package Method Example Dialog Box javax.swing showInputDialog(String) String w = JOptionPane.showInputDialog(null, "Enter name"); showMessageDialog(null, "Good Morning! "); showMessageDialog(String) Format java.text DecimalFormat n = new output class name = format(String) DecimalFormat(“00.00”) DecimalFormat To diplay decimal placeholder Mathematic Static methods abs(n) double x = Math.pow(4,2); al Methods in class Math pow(n1, n2) are used. sqrt(n1) round(n) min(x, y) Using Pre-defined classes 37 import java.util.*; import java.text.*; import java.math.*; public class preDefine { public static void main(String[] args) { Scanner inp = new Scanner(System.in); double price = 897878.89898656; String output; DecimalFormat decFormat = new DecimalFormat("000,000.00"); output = decFormat.format(price); System.out.println("Price: "+output+"\nSqrt(64): "+Math.sqrt(64)); System.out.println("Power (8^5): "+Math.pow(8,3)); } } Wrapper Classes 38  A wrapper class is defined as a class in which a primitive value is wrapped up. These primitive wrapper classes are used to represent primitive data type values as objects.  Java provides routine for converting String to a primitive data types or vice versa.  Below is wrapper class hierarchy as per Java API Wrapper Classes 39  It is called wrapper classes because the classes constructed by wrapping a class structure around the primitive data types Wrapper Method Description Example Class Integer parseInt(String) Converts a string to int int x = Integer.parseInt(s); Integer toString(x) Converts an int to string String s = Integer.toString(x); Long parseLong(string) Converts a string to long int Long x = Long.parseLong(s); Long toString(x) Converts a long int to string String s = Long.toString(x); Float parseFloat(s) Converts a string to float float x = Float.parseFloat(s); Float toString(x) Converts a float to string String s = Float.toString(x); Double parseDouble(s) Converts a string to double double x = Double.parseDouble(s); Double toString(x) Converts a double to string String s = Double.toString(x); References 40  Wu C. Thomas, An Introduction to Object-Oriented Programming with Java, 5th Edition, McGraw Hill , 2010  Cay Horstman, Big Java, John Wiley & Son, 2002  http://www.tutorialspoint.com/  http://www.explain-java.com/ Quiz 41 1. Which of the following is used for instantiate of an object? A. processor B. mutator. C. Constructor D. Retriever 2. ALL of the following statements are TRUE about methods of a class EXCEPT, A. accessor method is used to retrieve value of an object. B. a default constructor does not receive any parameter. C. mutator method is used to assign new values to an object. D. a processor method is used to initialize instance variables of an object.

Use Quizgecko on...
Browser
Browser