Fundamentals of Computing 1 - Lecture Title: Objects and Classes

Java OOPs Concepts Objects and Classes Method Overloading Constructor this keyword

ppt74 trang | Chia sẻ: nguyenlam99 | Lượt xem: 918 | Lượt tải: 0download
Bạn đang xem trước 20 trang tài liệu Fundamentals of Computing 1 - Lecture Title: Objects and Classes, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
Lecture Title: Objects and Classes Fundamentals of Computing 1AgendaJava OOPs ConceptsObjects and ClassesMethod OverloadingConstructorthis keywordOOPs (Object Oriented Programming System)Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: ObjectClassInheritancePolymorphismAbstractionEncapsulationWe will learn about these concepts one by one later.AgendaJava OOPs ConceptsObjects and ClassesMethod OverloadingConstructorthis keywordObjects and ClassesIn object-oriented programming, we design a program using objects and classes. Object is the physical entity whereas class is the logical entity. A class works as a template (blue print) from which we create the objects. Objects everywhere...Real world entitiesReal-World ObjectsStateBehaviorDogNameColorSexBarkRunSleepLampOnOffTurn onTurn offBicycleGearPedal cadenceBrakeChanging gear Changing pedalApplying brakesSoftware ObjectsSoftware objects are conceptually similar to real-world objectsAn Software object has three characteristics:identifier: represents the name of the object (name)state: represents the data of an object (fields)behavior: represents the behavior of an object (methods)ObjectsSoftware ObjectBicycle Software ObjectObject is a software entity that consists the fields and related methods.Fields are determined by specific values ​​called instance variables. A specific object is called an instance.In the real world, you'll often find many individual objects all of the same kind. The many individual objects of the same type share common features.Ex: Mountain bikes, road bikes, and tandem bikes, all share the common characteristics of bicycles (current speed, current pedal cadence, current gear)ClassesA class is a group of objects that have common property. It is the blueprint from which individual objects are created.Ex: Bicycle class is a blueprint for many bicycle object are createdClass defines the common fields and methods to all objects of the same kindClasses (cont.)An object is a specific instance of a class.ex: each Bicycle object (Mountain bikes, road bikes, and tandem bikes,) is an instance of the Bicycle class Each instance have different instance attributesex: a mountain bike might be in 5th gear while a road bike might be in 3rd gear.Classes (cont.)Example of Objects and Classes Bicycle ClassObjects of Bicycle ClassBasic approachWe have to notice four rules about Objects and Classes as followDefine classDeclare objectsCreate objectsUse objectsImportant order – step 1Define classDeclare objectsCreate objectsUse objectsDefining Class for creating Car ObjectsDefining class: Car Class What are the common attributes of cars?What are the common behaviors of cars?Defining Class: Car Class Carcolorspeedpowerdriveturn rightturn leftstopattributesoperationsclass nameDefining Car class in JavaCarString colorint speedint powerdrive()turnRight()turnLeft()stop()attributes or instance variablesmethodsclass nameDefining class: Java SyntaxA class in java can contain: data membermethodconstructorblockSyntax to declare a class:public class ClassName { data member; method; }Defining class: Example of Java Syntaxpublic class Car{// data membersprivate String color;private int speed;private int power;// methods public void drive() { // . } public void turnRight() { // . } public void turnLeft() { // . } public void stop() { // . }}CarString colorint speedint powerdrive()turnRight()turnLeft()stop()Important order – step 2Define classDeclare objectsCreate objectsUse objectsDeclaring objectsA class can be used to create objectsObjects are the instances of that classCarString colorint speedint powerdrive()turnRight()turnLeft()stop()newDeclaring object variablesA class name can be used as a type to declare an object reference variable Car car;An object reference variable holds the address of an objectDeclaring ObjectsCarString colorint speedint powerdrive()turnRight()turnLeft()stop()ClassCar car;caris of ClassImportant order – step 3Define classDeclare objectsCreate objectsUse objectsCreating ObjectsWe use the new keyword to create an objectcar= new Car();Creating an object is called instantiationAn object is an instance of a particular classWe can combine declaration and instantiation: carClassObjectinstance ofrefers toCar car= new Car();is of ClassCarString colorint speedint powerdrive()turnRight()turnLeft()stop()Important order – step 4Define classDeclare objectsCreate objectsUse objectsUsing objectsThe way you work with objects is to send them messagesMost statements using objects have the following structure object.data_member object.methodfor example: car.drive();This meansthe object whose name is caris sent the message driveSimple Example of Object and ClassOutput: null nullGo go go. I mean "Who are you"Instance variable and methodA variable that is created inside the class but outside the method, is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when object (instance) is created. That is why, it is known as instance variable. In java, a method is like function and is used to expose behavior of an object.Example of Object and class that maintains the records of studentsOutput: 111 Karan 222 AryanExample of Object and class that maintains the records of students (cont.)s1s2id=111name=Karanid=222name=AryanHeap MemoryRam MemoryAnother Example of Object and Classclass Rectangle{ int length; int width; void insert(int l,int w) { length=l; width=w; } void calculateArea() { System.out.println(length*width); }Output: 55 45public static void main(String args[]){ Rectangle r1=new Rectangle(); Rectangle r2=new Rectangle(); r1.insert(11,5);r2.insert(3,15);r1.calculateArea();r2.calculateArea(); } }AgendaJava OOPs ConceptsObjects and ClassesMethod OverloadingConstructorthis keywordMethod OverloadingIf a class have multiple methods by same name but different parameters, it is known as Method Overloading. Different ways to overload the methodThere are two ways to overload the method in javaBy changing number of argumentsBy changing the data typeNote: In java, Method Overloading is not possible by changing return type of the method.1. Example of Method Overloading by changing the number of argumentsOutput: 30 402.Example of Method Overloading by changing data type of argumentOutput: 21.0 40QuestionWhy Method Overloading is not possible by changing the return type of method?AnswerIn java, method overloading is not possible by changing the return type of the method because there may occur ambiguity.int result=obj.sum(20,20); /* Here how can java determine which sum() method should be called */QuestionCan we overload main() method?AnswerYes, by method overloading. You can have any number of main methods in a class by method overloading. Output: main() method invoked 10Method Overloading and TypePromotionOne type is promoted to another implicitly if no matching datatype is foundExample of Method Overloading with TypePromotionOne type is promoted to another implicitly if no matching datatype is foundOutput: 40 60Example of Method Overloading with TypePromotion if matching foundIf there are matching type arguments in the method, type promotion is not performed.Output: int arg method invokedExample of Method Overloading with TypePromotion in case ambiguityIf there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.Output: Compile Time ErrorAgendaJava OOPs ConceptsObjects and ClassesMethod OverloadingConstructorthis keywordConstructorConstructor is a special type of method that is used to initialize the state of an object.Constructor is invoked at the time of object creationConstructor is just like the instance method but it does not have any explicit return type.Rules for creating constructorThere are basically two rules defined for the constructor.Constructor name must be same as its class nameConstructor must have no explicit return typeTypes of constructorsThere are two types of constructors:default constructor (no-arg constructor)parameterized constructor1) Default ConstructorA constructor that have no parameter is known as default constructor.Syntax of default constructor: () { // constructor’s body }Example of default constructorIn this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. Output: Bike is createdRule of default constructorIf there is no constructor in a class, compiler automatically creates a default constructor.QuestionWhat is the purpose of default constructor?AnswerDefault constructor provides the default values to the object.Example of default constructor that displays the default valuesOutput: Student’s rollno : 0 Student’s name : null2) Parameterized constructorA constructor that have parameter is known as parameterized constructor.Example of parameterized constructorOutput: 111 Karan 222 AryanConstructor OverloadingConstructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.Example of Constructor OverloadingOutput: 111 Karan 0 222 Aryan 25Default initial valuesData typeInitial valuedouble, float0.0byte, short, int, long0char‘ ‘booleanfalseobject referencenullWhat is the difference between constructor and method ?ConstructorMethodConstructor is used to initialize the state of an object.Method is used to expose behaviour of an object.Constructor must not have return type.Method must have return type.Constructor is invoked implicitly.Method is invoked explicitly.The java compiler provides a default constructor if you don't have any constructor.Method is not provided by compiler in any case.Constructor name must be same as the class name.Method name may or may not be same as class name.AgendaJava OOPs ConceptsObjects and ClassesMethod OverloadingConstructorthis keywordthis keywordthis is a reference variable that refers to the object whose method is executingUsage of this keywordthis keyword can be used to refer current class instance variable. this() can be used to invoke current class constructor. this keyword can be used to invoke current class method (implicitly)1) The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguityUnderstanding the problem without this keywordOutput: 0 null 0 nullSolution of the above problem by this keywordOutput: 111 Karan 222 AryanSolution of the above problem by this keyword (cont.)Program where this keyword is not requiredOutput: 111 Karan 222 AryanIf local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program2) this() can be used to invoked current class constructor. The this() constructor call can be used to invoke the current class constructor. This approach is better if you have many constructors in the class and want to reuse that constructor.Output: default constructor is invoked default constructor is invoked 111 Karan 222 AryanRule: Call to this() must be the first statement.3)The this keyword can be used to invoke current class method (implicitly).Output: method is invoked222 Aryan3)The this keyword can be used to invoke current class method (cont.)What we have coveredJava OOPs ConceptsObjects and ClassesMethod OverloadingConstructorthis keyword

Các file đính kèm theo tài liệu này:

  • pptlecture_08_class_and_object_6882.ppt