Lecture 2 Classes and objects, Constructors, Arrays and vectors.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Java Programming 2 Dr. Priti Srinivas Sajja Introductory concepts of java programming as specified in PGDCA 203:Object Technology, S P University.
1 CLASSES. 2 Class Fundamentals It defines a new data type Once defined, this new type can be used to create objects of that type A class is a template.
Chapter 7: User-Defined Functions II
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Metode di Java Risanuri Hidayat, Ir., M.Sc.. Pendahuluan Classes usually consist of two things: instance variables and methods. The topic of methods is.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
04/07/041 Intro to JAVA By: Riyaz Malbari. 04/07/042 History of JAVA  Came into existence at Sun Microsystems, Inc. in  Was initially called “
Lecture From Chapter 6 & /8/10 1 Method of Classes.
Review of C++ Programming Part II Sheng-Fang Huang.
Java Unit 9: Arrays Declaring and Processing Arrays.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
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.
CSC Programming I Lecture 8 September 9, 2002.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
class Box { Box is new data type of the class. double width;
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
A Closer Look at Methods and Classes. Overloading Methods In Java it is possible to define two or more methods within the same class that share the same.
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.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Learners Support Publications Classes and Objects.
Overloading There is another aspect to polymorphism: Overloading Overloading is not overriding. In Turkish: Overridding: eskisini (geçersiz kılmak) Overloading:
Object-Oriented Programming in C++
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
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.
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.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
 Constructor  Finalize() method  this keyword  Method Overloading  Constructor Overloading  Object As an Argument  Returning Objects.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
What is an Object? Real world objects are things that have: 1) state 2) behavior Example: your dog: 1) state – name, color, breed, sits?, barks?, wages.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
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.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Classes, Interfaces and Packages
Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 CLASSES. 2 Class Fundamentals It defines a new data type Once defined, this new type can be used to create objects of that type A class is a template.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Topics Instance variables, set and get methods Encapsulation
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Methods and Classes. Method Overloading Two or more methods within the same class that share the same name but different parameters class OverloadDemo.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
OOP Features Object Oriented Programming Main issues in software engineering – –maintainability, reusability, portability, security, integrity, user.
Topic: 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.
This pointer, Dynamic memory allocation, Constructors and Destructor
Constructor Overloading
Introduction to Classes
OBJECT ORIENTED PROGRAMMING
Classes and Objects.
JAVA 22 February 2019 DEPARTMENT OF CSE.
Method of Classes Chapter 7, page 155 Lecture /4/6.
Java Programming Language
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
class Box { double width; double height; double depth; }
Presentation transcript:

Lecture 2 Classes and objects, Constructors, Arrays and vectors

Class Fundamentals Class defines a new data types Once defined, this new type can be used to create objects of that type Class is a template for an object and, an object is an instance of a class The data or variables, defined within a class are called instance variables The code is contained within methods Collectively, the methods and variables defined within a class are called members of a class

The General Form of a Class class classname{ type instance-variable1 //… type instance-variable N type methodname1(parameter-list){ //body of the method } type methodname N(parameter-list){

Caution General form of a class does not specify a main( ) method Class declaration and implementation of the methods are stored in the same place and not defined separately (Different from the C++) Sometimes .java files become very large

A Simple Class class Box{ double width; double height; double depth; } This code does not cause any objects of type Box to come into existence To actually create a Box object, you will use a statement like: Box mybox = new Box(); // create a Box object called mybox

Example:BoxDemo.java Here is a complete program that uses the Box class class Box { double width; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol);

Declaring Objects To obtain objects of a class, we need First declare a variable of the class type Second, acquire an actual, physical copy of the object and assign it to that variable (by new operator) In Java, all class objects must be dynamically allocated Object references appear to be similar to pointers, but you can not manipulate references as you actual pointers

Declaring Objects (cont.) Statement Effect Box mybox; mybox mybox=new Box( ); Box object null Width Height Depth

A Closer Look at new mybox=new Box(); The class name followed by parentheses specifies the constructor for the class If a class don’t explicitly define its own constructor, the Java automatically supply a default constructor We don’t need to use new for integers or characters. Because java’s simple types are not implemented as objects It is possible that new will not be able to allocate memory for an object because of insufficient memory. In that case, a run-time exception will occur

Assigning Object Reference Variables Box b1=mew Box(); Box b2=b1; b1 and b2 will both refer to the same object b1 b2 Box object If b1 is assigned null (b1=null;), the b2 still points to the original object Width Height Depth

Introducing Methods class Box { double width; double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; // display volume of first box mybox1.volume();

Returning a Value class Box { double width; double height; double depth; double volume( ) { // compute and return volume return width * height * depth; } class BoxDemo4 { public static void main(String args[ ]) { Box mybox1 = new Box(); double vol; mybox1.width = 10; // assign values to mybox1's instance variables mybox1.height = 20; mybox1.depth = 15; vol = mybox1.volume( ); // get volume of first box System.out.println("Volume is " + vol);

Methods having Parameters There are two problems in the previous code Its is clumsy and error prone (you may forget to set dimension) Instance variables should be accessed only through methods defined by their class void setDim(double w, double h, double d) { width = w; height = h; depth = d; } mybox1.setDim(10, 20, 15);

Constructors A constructor is automatically called immediately after the object is created, before the new operator completes Its has no return types, not even void Constructors have the same name as the classname When we write Box mybox1=new Box( ); actually the constructor for the class is being called As you know, Java creates a default constructor for the class, which initializes all instance variables to zero

Constructor example Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } When you write Box mybox1=new Box( ); the values of height, width and depth are automatically assigned

Parameterized Constructors Box(double w, double h, double d) { width = w; height = h; depth = d; } Box mybox1 = new Box(10, 20, 15);

The this keyword Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword this can be used inside any method to refer to the current object. this always refers to the object on which the method was invoked Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; }

Where this actually used When a local variable has the same name as an instance variable, the local variable hides instance variable. This is why width, height and depth were not used as the names of the parameters to the Box( ) Although here we can use different names, but you can resolve any name space collisions by this, which lets you refer directly to the object Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }

Garbage Collection In C++, dynamically allocated objects must be manually released by use of delete operator Java takes a different approach; it handles deallocation for you automatically When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed Garbage collection only occurs sporadically during the execution of your program

The finalize() Method Sometimes an object will need to perform some action when it is destroyed (i.e. release some non-java resources such as file handle or windows character font) finalize( ) method allows us to define specific actions that will occurs when an object is just about to be reclaimed by the garbage collector protected void finalize( ) { //finalization code here } You cannot know when- or even if- finalize( ) will be executed. Therefore, you must not rely on it for normal program execution

A Closer Look at Methods and Classes

Overloading methods (polymorphism) Defining two methods within the same class that share the same name, as long as their declarations are different Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call The return type alone is insufficient to distinguish two versions of a methods

Example class Overload { public static void main(String args[ ]) { class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; class Overload { public static void main(String args[ ]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.2); System.out.println("Result of ob.test(123.2): " + result); }

Automatic type conversion class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double) } class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); // overload test for a double parameter and return type void test(double a) { System.out.println("Inside test(double) a: " + a);

Overloading Constructors

Using Objects as Parameters Thus one object can be used to initialize another object Objects are always passed by reference

Returning Objects

Introducing Access Control (Encapsulation) When correctly implemented, a class creates a “black box” which may be used, but inner workings of which are not open to tampering When a member of a class is specified as private, then that member can only be accessed by other members of its class By default, the member of a class is public within its own package, but cannot be accessed outside of its package

Example

Example:Stack

Understanding Static It is possible to create a member that can be used by itself, without reference to a specific instance. To create such a member, precede its declaration with the keyword static Both methods and variables can be static Instance variables declared as static are, essentially, global variables When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable Methods declared as static have several restrictions: They can only call other static methods They must only access static data They cannot refer to this or super any way

Output: Static block initialized X=42 A=3 B=12 Example

Introducing final A variable can be declared as final, which prevents its contents from being modified final is similar to const in C/C++ final variable must be initialized when it is declared Common convention is to use uppercase identifiers for final variables The keyword final can also be applied to methods Example: final int FILE_OPEN=2;

More about arrays Arrays can be implemented as objects i.e. length instance variable of an array class Length { public static void main(String args[]) { int a1[] = new int[10]; int a2[] = {3, 5, 7, 1, 8, 99, 44, -10}; int a3[] = {4, 3, 2, 1}; System.out.println("length of a1 is " + a1.length); System.out.println("length of a2 is " + a2.length); System.out.println("length of a3 is " + a3.length); }

Introducing Nested and Inner Classes The scope of nested class is bounded by the scope of its enclosing class A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class There are two types of nested class: Static (it cannot refer to members of its enclosing class directly) Non-static/inner (it has access to all of the variables and methods of its outer class directly)

Example

Exploring the String class Every string you create is actually an object of type String. Even string constants are actually String objects String objects are immutable; once a String object is created, its contents cannot be altered Java defines a peer class of String, called StringBuffer, which allows strings to be altered One way to create a string is: String mystring=“this is a test” + operator is used to concatenate two strings

Some String methods equals( ) is used to test two string for equality length( ) is used to obtain the length of string charAt( ) is used to obtain the character at a specified index within a string Also you can have arrays of string String str[ ]={“one”, “two”, “three”};

Example

Using Command-Line Arguments Helps us to pass information into a program when it is run class CommandLine { public static void main(String args[]) { for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } To execute a program, we write from the command prompt: java CommandLine this is a test 100 -1