0% found this document useful (0 votes)
37 views26 pages

CMP 202 - 1

Camp 201 lectures pdf

Uploaded by

Sanusi Mansur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
37 views26 pages

CMP 202 - 1

Camp 201 lectures pdf

Uploaded by

Sanusi Mansur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 26
PART A CMP202: COMPUTER PROGRAMMING II PRINCIPLES OF GOOD PROGRAMMING Programming principles are essential guidelines that help programmers to create effic maintainable, and scalable software solutions. These principles serve as the foundation for developing robust and flexible code, enabling developers to write code that is casier to understand, modify, and extend. As we already know that, itis always easy for a programmer to write codes, but it becomes a difficult task to write clean, well-structured, and easy-to-read codes. Therefore, writing clean code is a task every programmer should practice, ‘The programmer should bear in your minds that he is not the only person who will deal with his programs. As such embracing the basic programming principles is a sure-fire way to write high-quality code that is efficient, readable, reliable, secure, and maintainable, regardless of the size of a software application you are dealing with. These principles of programming are a roadmap to becoming a professional programmer. In this lecture, we will explore some good programming practices that will help make you a better Java programmer. Some Good Programming Practices 1. Write your Java programs in a simple and straightforward manner. This is sometimes referred to as KIS ("keep it simple"). Do not "stretch" the language by trying bizarre usages. Read the documentation for the version of Java you are using. Refer to it frequently to be sure you are aware of the rich collection of Java features and are using them correctly. 3. Your computer and compiler are good teachers. If, after carefully reading your Java documentation manual, you are not sure how a feature of Java works, experiment and see what happens. Study each error or warming message you get when you compile your programs (called compile-time errors or compilation errors), and correct the programs to eliminate these messages. 4, Every program should begin with a comment that explains the purpose of the program. 5. Use blank lines and space characters to enhance program readability. fier with a capital letter and start each 6. By convention, always begin a class name's ider subsequent word in the identifier with a capital letter. Java programmers know that pel PART LA such identifiers normally represent Java classes, so naming yout classes in this mannet makes your programs more readable 7. Whenever you type an opening heft brace, |, in your program, immediately type the losing right brace, }. then repasition the cursor between the braces arm) indent to begin typing the body. This practice helps prevent er 8. Indeat the entire bly of cach class declaration/‘method one “level” of indentation between the left bree. (, and the right brace, ), that delimit the body of the class methos. This format emphasizes the class/nethod declaration’s structure and makes it easier w read. 9. Following the closing right brace ()) of a method body or class declaration with an due to missing braces easofline comment indicating the method or class declaration to which the brace belongs improves program readability, 20. Place a space after cach comma (,) in an argument list to make programs more readable. 11, Declare each variable on a separate line. This format allows a descriptive comment to be easily inserted next to each declaration. 12. Choosing meaningful variable names helps a program to be self-documenting (i.¢., one can understand the program simply by reading it rather than by reading manuals or viewing an excessive number of comments). 13. By convention, variable-name identifiers begin with a lowercase letter, and every word in the name after the first word begins with a capital letter. For example, variable-name identifier ¢irstNunber has a capital w in its second word, tuber. 14, Place spaces on either side of a binary operator to make it stand out and make the program more readable. 15. Using parentheses for complex arithmetic expressions, even when the parentheses are not necessary, can make the arithmetic expressions easier to read. 16, Indent an s¢ statement's body to make it stand out and to enhance program readability. 17, Place only one statement per line in a program. This format enhances program readability. 18. Refer to the operator precedence rules (already leamt in CMP201) when writing expressions containing many operators. Confirm that the operations in the expression are performed in the order you expect. If you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, exactly as you pe.2 20. 21. 24. asx 26. 27. PART I-A would do in algebraic expressions. Observe that some operators, such as assignment, =, associate from right to left rather than from left to right. . Place a blank line between method declarations to separate the methods and enhance program readability. Separate declarations from other statements in methods with a blank line for readability. In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the user of the sentinel value. . The unary increment and decrement operators should be placed next to their operands, with no intervening spaces. Place blank lines above and below repetition and selection control statements, and indent the statement bodies to enhance readability. Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear cither before the loop (if they execute only once, like initialization statements) or in the body of the loop (if they execute once per iteration of the loop, like increment or decrement statements). Always include braces in a do. . .while statement, even if they are not necessary. This helps eliminate ambiguity between the white statement and a do... .while statement containing only one statement. Although each case and the default case in a switch can occur in any order, place the default case last. When the default case is listed last, the break for that case is not required. Some programmers include this break for clarity and symmetry with other cases. . The online Java API documentation is easy to search and provides many details about each class. As you leam a class in this course, you should get in the habit of looking at the class in the online documentation for additional information. VARTA OBJECT ORIENTED PROGRAMMING CONCER' Object-orientation is a new technology based on objects und classes, Object Oriented Programming (OOP) is a methodology or parutigm to design a program using classes and objects. OOP is a model where by a problem domain is modelled into objects, so that problem solving is by interaction among objects. It is a type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure, Examples of OOP languages are C++, JAVA, Cll, PHYTHON etc. It simplifies software development and maintenance by providing some concepts: Encapsulation Object An object is an individual, identifiable entity, either real or abstract, that has a well-defined boundary. It has two characteristics (attributes (state) & methods (behaviour)). It is one of the main ingredients of OOP. Some of the real-world objects are book, mo! etc. An object is a variable of the type class; it is a basic component of an object-oriented programming system. A class has the methods and data members (attributes), these methods and data members are accessed through an object. Thus, an object is an instance of a class, Attributes are the data component of an object that define the descriptive characteristics of an object e.g. your car is brown in colour, your mobile is branded “Nokia”. Methods are the procedural component of an object that define the behaviour of an object e.g. a car moves, a mobile sends SMS. Example 1: You, the student following this Lecture, are an object. Your attributes include your name, your GPA, your course of study etc. You also have a set of behaviour, including attending lectures, solving assignments, telling someone your GPA etc. , table, computer, ped PART EA Example 2: If you are asked to write a bank account program, What are the objects, attributers and methods? The bank account is an object; the owner of the bank account is also an object, The bank account object has opening deposit, balance (amount of money in the account) and name of account as attributes. The bank account object can have a method which it uses to calculate its balance. Class A class is a blueprint from which individual objects are created (or, we can say a class is a data type of an object type). In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and manipulated through the objects. The Objects of the same class have the same set of attributes & methods, Each object is an instance of a class. It shares the behaviour of the class, but has specific values for the attributes. Example 3: The following table shows examples of classes and their instances: Classes Instances of (or Objects) Lecturer A. Almu University bus Course CMP202 Inheritance Inheritance is a process by which we can reuse the functionalities of existing classes to new classes, In the concept of inheritance, there are two terms base (parent) class and derived (child) class, When a class is inherited from another class (base class), it (derived class) obtains all the properties and behaviors of the base class. Example 4: The real life example of inheritance is child and parents, all the properties of father are inherited by his son. Examaple 5: Consider the following example that shows a Student class and its related sub- classes: PART LA Student GraduateStudent DiplomaStudent MssStudent ] PhDStudent Polymorphism The term "polymorphism" means "many forms". Polymorphism is useful when you want to create multiple forms with the same name of a single entity. To implement polymorphism in Java, we use two concepts method overloading and method overriding. The method overloading is performed in the same class where we have multiple methods with the same name but different parameters, whereas, the method overriding is performed by using the inheritance where we can have multiple methods with the same name in parent and child classes. Example 6: A person at the same time can have different characteristics. Like a man at the same time is a father, a husband, and an employee. So the same person possesses different behaviours in different situations. This is called polymorphism. Abstraction Abstraction is a technique of hiding intemal details and showing functionalities. The abstract classes and interfaces are used to achieve abstraction in Java. Example 7: When you consider the case of e-mail, complex details such as what happens as soon as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore, to send an e-mail you just need to type the content, mention the address of the receiver, and click send. Encapsulation Encapsulation is a process of binding the data members (attributes) and methods together. The encapsulation restricts direct access to important data, The best example of the encapsulation concept is making a class where the data members are private and methods are public to access, through an object. In this case, only methods can access those private data. Example 8: Consider your school or office bag. The bag contains different stuffs like pen, pencil, notebook ete within it, in order to get any stuff you need to open that bag, similarly in PB. 6 PART be java an encapsulation unit contains it's data and bebaviour within it and in order to access them you need an object of that unit, Advantages of OOP The following are some advantages of using the OOP in Java: Ll. 2. 4: The implementations of OOP concepts are easier. The execution of the OOP is faster than procedural-oriented programming. OOP provide code reusability so that a programmer can reuse an existing code. Because by using inheritance, the redundant code can be eliminated by extending the use of existing classes. OOP helps us to keep the important data hidden. Encapsulation enables objects to be self-contained, making troubleshooting and collaborative development easier. It is possible to map the objects in problem domain to those in the program. PART ED CLASSES, OBJECTS, ATTRIBUTES AND METHODS CLASS: Remember that, a class is a blueprint from which individual objects are created. For example, if you want to create a class for students, In that case, "Student" will be a class, and student records (like student], student2, ete) will be objects The graphical representation of a class and its clements in form of a UML diagram is as follows: Attributes ‘Consider the following Student class as a typical example in form of a UML diagram: ‘Student studentID name spa getName changeGPA getlD The Class naming convention: 1, Noun or Noun phrase 2. First letter of each word capitalized, No underscores. Examples: Book, DatePalm, Student, GraduateStudent, Bank Account ete. Creating (Declaring) a Java Class To create (declare) a class, you need to use access modifiers followed by elass keyword and class_name, The syntax to create (declare) class in Java is as follows: access modifier class ClassName{ attributes; constructors; methods; Example: public class Student{ 1 PART Access Modifiers Access modifiers are Java key words that are used to qualify classes, methods and attributes. In Java we have three access modifiers called Public, Private and Protected. For now let's consider Public and Private, ‘The keyword Public is used to indicate that a method, class or attribute is available to the public, that is, it can be called from outside the class declarations body by methods of other classes. ‘The keyword Privae is used to indicate that a method, class or attribute is not available to the public, that is, it cannot be called from outside the class declarations body by methods of other classes. Normally, classes and methods are declared Public, while attributes are declared Private. However we shalll see later that some methods can be declared as private while some attributes ‘can be declared as public. Class Attributes Attributes are the distinctive characteristic, quality, or feature that contributes to make objects ofa class unique. Each attribute has a value. An attribute could be of simple type or it could be another class type. Some attribute values change over time. Objects store their attribute values in instance variables. It is good practice to make attributes private. Attributes: Syntax & Naming Attribute naming convention: 1. ‘Noun, noun phrase or adjective 2. Starts with small letter and each phrase's first letter capitalized Good attribute names | Bad attribute names readBook Color yearlySalary vyearlysalary accessModifier type altributeName; accessModifier type attributeName = initial Value; Example: private int id; private double gpa; PART ED Methods Methods are the actions that an object performs. Through methods objects interact and pass messages to other objects. The behavior of an object depends on its attribute values and the operations performed upon it Methods: Syntax & Naming Method naming convention: 1. Verb or verb phrase 2. Starts with small letter and each phrases first Letter capitalized Good method names Bad method names getName, GetName changeGPA studentinformation| TeeisterCourse playfootball ‘Syntax: modifier returnType methodName(parameterType parameter, . ..){ statements return expression; Example: public double calculateAverage(int valuel, int value2){ double average = (valuel + value2) / 2.0; return average; } Return Type of a Method As you can notice from the method above each method has a return type that is written before ‘the method name. The return type is used to indicate the data type of the attribute which the ‘method will return when itis called, For example: public String getName is a method whose retum type is a String. The meaning of this is that when this method is called, it is going to return a variable whose data type is a String ie. “Mubashshir”. public double getName is a method whose retum type is an integer. This means it will return a variable whose data type is an double. Also, note that some methods do not return anything when they are called. In such methods the keyword void is used to indicate that the method will not return anything. Let's consider the following method: public void calculateSalary ( pg. 10 PART ED salary = basicPay + houseAllowance - taxes; ) ‘The method name is calculateSalary. The return type is void i.c. it does not return anything when it is called. When the method is called, it only calculates the salary and stores the value. The body of the method contains a formula which helps it to calculate Instance Variables State of an. object: the set of values that describe the object. Each object stores its state in one or more instance variables. private double gpa ; Scope of an Instance variable: the part of the program in which you can access the variable. In Java, the scope of a variable is the block in which that variable is declared. Private instance variables can be accessed directly only in the methods of the same class. We can gain access to private instance variables through public methods in that class. Each object of a class has its own copy of an instance variable. Constructors In addition to instance variables and methods, a class may have one or more constructors. Constructors are used to initialize the instance variables of an object at the time of creating the object. Question: What is the difference between a constructor and a method? 1. Aconstructor: 1. Dees not nav 2: Must have ti 2, It is invoked by the new operator. pa. tl PART IB WRITING JAVA PROGRAMS USING CLASSES You will recall that all the programs we wrote in CMP201 inelude only one class and one method i.e. the main method. But now we are going to do programming involving classes and objects i.e. in OOP way. Example 1: Class declaration with one method to be saved as GradeBook,java public class GradeBook 1 // display a welcome message to the GradeBook user public void displayMessage() { System.out.println( "Welcome to the Grade Boo } // end method displayMessage ) // end class GradeBook Now the next thing is to ereate an object of class GradeBook and calling its displayMessage method to be saved as GradeBookTest java. public class GradeBookTest { // main method begins program execution public static void main( String args{] ) { // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook () + // call myGradeBook"s displayMessage method myGradeBook.displayMessage () ) // end main } // end class GradeBookTest As mentioned previously, a class provides the blueprints for objects. So basically, 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: 1. Declaration: A variable declaration with a variable name with an object type. 2, Instantiation: The ‘new’ keyword is used to create the object. 3, Initialization: The ‘new’ keyword is followed by a call to a constructor. This call initializes the new object. Syntax: PART The symtax to create an object of the class in Java: Class name object_name = new Class_name({parameters]); Note: parameters are optional and can be used while you're using constructors in the class. For instance, an object can be created from the Student class as follows: Student thisStudent = new Student (993546, "Sadiq Sani, 3.5); ‘Affer creating the object, then you can use the object to call any of the methods inside the class. The method to call depends on what task you want to perform, Remember that each class usually has many methods. To call a method you use the following syntax: Objecmame.methodname(): Example 2; Our next example declares class GradeBook with a displayMessage method that displays the course name as part of the welcome message. But, now the new displayMessage method requires a parameter that represents the course name to output. Class declaration with one method that has a parameter to be saved as GradeBook.java public class GradeBook i // display a welcome message to the GradeBook user public void displayMessage( String courseName ) { System.out.printf£( "Welcome to the grade book for\nts\n", courseName ); ) // end method displayMessage } // end class GradeBook Creating a GradeBook object and passing a String to its displayMessage method. to be saved as GradeBookTest java import java.util.Scanner; // program uses Scanner public class GradeBookTest { // main method begins program execution public static void main( String args(] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in }; /f create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook(); // prompt for and input course name System.out.printin( "Please enter the course name:" ); String nameOfCourse = input.nextLine ()7 //read a line of text pg. 13 PART Ls System.out-printin(); // outputs a blank Line // call myGradeBook's displayMessage method // and pass nameOfCourse as an argument myGradeBook.displayMessage( nameOfCourse ); } // end main } /f end class GradeBookTest Example 3: Write a program that uses classes and objects to display the studentID, Name and GPA of some student: Solution Note that, this class must be stored in a file called: Student.java public class Student( private int id; private String name; private double gpa; public Student (int theID, String theName, double theGPA) ( id = theID; name = theName; gpa = theGPA; } public String getName () { return name; public int get1D(){ return id; d public double getGPA(){ return gpa; , ) Note that, this class must be stored in a file called: TestStudent,java public class TestStudent( public static void main(String[] args) { Student student = new Student (999999, “Ahmad Muhammad”, 3.2); System.out.print1n("Name: “ + student.getName()); System. out .print1n(“IDi “ + student.getID()); System. out .println("GPA: “ +student.getGPA()); pe.l4 PART 1-8 Note; Two or more classes may be placed in a single Java file, In that case: 1, Only one class can be public; namely the class containing the main method. 2. The name of the Java file must be that of the public class. Set and Get methods According to its return type, a method can be classified into two types: get and set methods. Any method that returns a value when it is called is known as a Get method, while any method that does not retum a value when it is called is known as a Sef method. Public and Static Class Methods There are two types of class methods public and static class method. The public class methods are accessed through the objects whereas; the static class methods are accessed without an object. Example 4: GradeBook Class with an Instance Variable, a set Method and a get Method In our next application, the class GradeBook maintains the course name as an instance variable so that it can be used or modified at any time during an application's execution. The class contains three methods. setCourseName, © getCourseName and displayMessage. Method setCourseName stores a course name in a GradeBook. Method getCourseName obtains a GradeBook's course name. Method displayMessagewhich now specifies no parameters still displays a welcome message that includes the course name. However, as you will see, the method now obtains the course name by calling another method in the same classgetCourseName. GradeBook class that contains a courseName instance variable is as follows: public class GradeBook { private String courseName; // course name for this GradeBook // method to set the course name public void setCourseName( String name ) { courseName = name; // store the course name } // end method setCourseName // method to retrieve the course name Public String getCourseName() pg. 15 PART LD return courseName; } // end method getCourseName // display a welcome message to the GradeBook user public void displayMessage() { // this statement calls getCourseName to get the // name of the course this GradeBook represents System.out.print£( "Welcome to the grade book for\nts!\n", getCourseName() ); } // end method displayMessage } // end class GradeBook Class GradeBookTest creates one object of class GradeBook (Creating and manipulating a GradeBook object) and demonstrates its methods as follows: import java.util.Scanner; // program uses Scanner public class GradeBookTest { // main method begins program execution public static void main( String args{] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); // create a GradeBook object and assign it to myGradeBook GradeBook myGradeBook = new GradeBook () 7 // display initial value of courseName System.out.printf( "Initial course name is: %s\n\n", myGradeBook. getCourseName() ) 7 // prompt for and read course name System.out.println( "Please enter the course namei" ); String theName = input.nextLine(); // read a line of text myGradeBook.setCourseName( theName ); // set the course name System. out.printin(); // outputs a blank line // display welcome message after specifying course name myGradeBook. displayMessage (); } // end main } // end class GradeBookTest pe. 16 | — PART LC INHERITANCE Inheritance is a mechanism for enhancing existing, working classes. A new class can inherit from a more general existing class. Consider the diagram below Let consider the above diagram, then the Child Class can have the following attributes and methods: The Attributes are: % Inherited: a,b > not inherited: c The Methods are: + Inherited: opl() , 0p2() not inherited: op3() Note: Constructors and private members of a class are not inherited by its subclasses. ‘Superclass and Subclass Superclass (base class, parent class): A general class from which a more specialized class (a subelass) inherits. Subclass (derived class, child class): A class that inherits variables and methods from a superclass but adds instance variables, adds methods, or redefines inherited methods. Consider the following examples: pg. 17 813d 1()ureW seu = [qo uTeH (ute) sseTo paatzap aya Jo qoelqo HuTIwezD // } ({)s62e Surz3g)uyew ptoa oTqe3s OTTGNd } 2uUO spuagxe uTeN sseTo OTTaNd ( { f(,°S8eT2 eu JO poyzau ()euOIUTZd,,) UTIUTId~yno‘weIshs } (eugqutsd ptoa oTtaqnd } ug sseTo sapoo eave Sumoltos atp z9pesuo | aydurexsy “ssvpo paauap uo Ajuo 0} ss@jo aseq au Kuo wo HEP swLEqU aoUNEYU! (jena]-/SuIs “I0) a/SuIs oy “souEyUT 2fSuys se uavouy st ssefo paAlzap 2U0 pur sseId aseq JU0 ATUO st aL9Up YSTYA UH BDuEIUOYUT ULL aoueqaquy 9[3uIS, :SMO[Joy se are sadAy ayy, “ss¥]O au0: UNL az0UE pa2yxo jour sselo BIBI SHBAU StH] “SOUEWAYU pLrqdy] pue aydiy{nyy Hoddns you saop wavy “Teoryausang pur “ppAasqpInyy ‘91BuIg ssoumudyUr Jo sadky somp AqureUL axe auoq “Avy UY soueyiaquy yo ssc, -yaa{qo ue st juapnys aqenpels yg -asinoo v st asmoo auyJuo UY -9smoo v s1 asmo> WOUSY 4 “wapnys v st apna awenpLId yey sojdurexa 104 199(go vem Jo 204 auyjap ated ssejosodns-ssejoqns y dyysuonyejaa y sy vst yolgo sry, :SurXes yo kem v st 1] “drysuonejan Vy ota PART EC J// Calling method obj.printone(); ) Multilevel Inheritance The inheritance in which a base class és inherited to a derived class and that derived class is further inherited to another derived class is known as multi-level inheritance. Multilevel inheritance involves multiple base classes, Example 2: Consider the following codes class One { public void printone() { System.out.printin("printOne() method of One class. ) , class Two extends One { public void printTwo() { System.out.print1n("printTwo() method of Two class."); } ) public class Main extends Two { public static void main(String args{]) { // Creating object of the derived class (Main) Main obj = new Main(); // Calling methods obj.printOne() 7 obj .printTwo(); Hierarchical Inberitance The inheritance in which only one base class and multiple derived classes is known as hierarchical inheritance. Example 3: Consider the following codes, class One { // Base class public void printOne() { System.out.print1n("printOne() Method of Class One"); } ) // Derived class 1 class Two extends One | Public void printTwo() ( Pg: 19 PART LC System.out.printin("Two() Method of Class Two"); ) } #/ Derived class 2 class Three extends One { public void printThree() | System.out.printin("printThree() Method of Class Three"); } ' // Testing Class public class Main { public static void main(String args{]) | Two obj1 = new Two(); Three obj2 = new Three ()z //AL1l classes can access the method of class One obj1.printOne() ; obj2.printOne(); Why Inheritance? The following are some of the reasons for using inheritance in programming: Code Reusability: The basic need of an inheritance is to reuse the features. If you have defined some functionality once, by using the inheritance you can easily use them in other classes and packages. Extensibility: The inheritance helps to extend the functionalities of a class. If you have a base class with some functionalities, you can extend them by using the inheritance in the derived class. Method Overriding: Inheritance is required to achieve one of the concepts of Polymorphism which is Method overriding. Implementation of Inheritance in Ja To implement inheritance in Java, extends keyword is used. It inherits the properties (attributes or/and methods) of the base class to the derived class. The word "extends" means to extend functionalities i.¢., the extensibility of the features. Consider the following syntax used to implement inheritance in Java: class SuperclassName { PART EC class SubclassName extends SuperclassName Example: class GraduateStudent extends Student { String thesisTitle; defendThesis(){. . .) Final Class Acclass that is declared as final cannot be extended or subclassed. final class className { variables methods ) Examples of final classes are: java.lang.System, © The primitive type wrapper classes: Byte, Character, Short, Integer, Long, Float, and Double. Class Hierarchy In Java, every class that does not extend another class is a subclass of the Object class. This means that, it is defined in the java.lang package. Thus, classes in Java form a hierarchy, with the Object class as the root. Example of a class hierarchy: Sbjoct pg. 21 PART EC Subclass Constructors To initialize instance variables of a superclass, a subclass constructor invokes a constructor of its superelass by a call of the form: super{parancters); This statement must be the first statement within the constructor, Example 4: Consider the following constructor of a GraduateStudent class public GraduateStudent (int id, String name, double gpa, String thesisTitle) { super(id, name, gpa); this. thesisTitle = thesisTitle; ' If the first statement in a constructor does not explicitly invoke another constructor with this or super; Java implicitly inserts the call: super( );. Constructor calls are chained; any time an object is created, a sequence of constructors is invoked: from subclass to superclass on up to the Object class at the root of the class hierarchy. Example 5: Consider the following Calculation and MyCalculation classes. public class Calculation { protected int 2; public void addition(int x, int y) { zextyr System.out.println("The sum of the given numbers:"+2); ' Public void Subtraction(int x, int y) { zex-yr System.out.println("The difference between the given numbers: "+z ’ ) public class MyCalculation extends Calculation { public void multiplication(int x, int y) ( ee x tyr System.out.println("The product of the given numbers:"+z); ’ public static void main(String args(]) { int a= 20, b = 10; MyCalculation calculate = new MyCalculation(); calculate.addition (a, b); calculate.Subtraction(a, b); ealculate.multiplication(a, b); PART LC ‘Access Modifiers ‘Access Modifier Members with the access modifier can be accessed directly by: Private Methods of their own class only. Protected Methods of their own class. ~ ‘Methods of subclasses and other classes in thesame package. Methods of subclasses in different packages, Public Methods of all classes in all packages. Methods in Subclasses A method in a subelass can be: Anew method defined by the subclass. 4 Amethod inherited from a superclass. ¢ Amethod that redefines (ie., overrides) a superclass method. ‘Method Overriding A subclass overrides a method it inherits from its superclass if it defines a method with the ‘same name, same return type, and same parameters as the supercalss method. For instance, each of the following causes compilation error: 4 The overriding method has the same signature but different return type to the method it is overriding, Amethod declared as final, final retumType methodNamef ....), cannot be overridden. Note: We have already come across examples of method overriding when we discussed the redefinition of the toString methods under class hierarchy. Example 6: Consider the following method overriding example public class Student{ private int id; private String name; private double gpa; public String toString() { return “ID: “ + id + “,Name: “ + name + “, GPA: “ + gpaz ) ) public class GraduateStudent extends Student { string thesisTitle; public String toString() ( return super.toString() +“, Thesis Title:” + thesisTitle; } Pe. 23 PARTIC POLYMORPHISM. Polymorphism is the ability of an object to take on many forms. It allows us to perform multiple operations by using the single name of any method (interface). Any Java object that ccan pass more than one IS-A test is considered to be polymorphie. In Java, all Java objects are polymorphic since any object will pass the IS-A test for its own type and for the class Object. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. It is important to know that the only possible way to access an object is through a reference variable, A reference variable can be of only one type, Once declared, the type of a reference variable cannot be changed. The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object. Polymorphism Implementation in Java Like we already specified in the previous section; Inheritance lets us inherit attributes and ‘methods from another class. Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways. For example, think of a superclass called Animal that has a method called animalSoundQ, Subclasses of Animals could be Pigs, Cats, Dogs, Birds and they also have their own implementation of an animal sound like say a cat meows. Then let look at the Java implementation of the above case as follows: class Animal { public void animalSound() { System.out.println("The animal makes a sound"); ) , class Pig extends Animal { public void animalSound() { System.out.println("The pig says: wee wee"); ) , class Dog extends Animal { public void animalSound() { System.out.println("The dog says: bow wow"); } ) ‘Types of Polymorphism There are two types of polymorphism in Java: These are Compile Time Polymorphism and Run Time Polymorphism. pe.24 PART LC Compile Time Polymorphism ‘Compile-time polymorphism is also known as static polymorphism and it is implemented by method overloading. Example 7: This example has multiple methods having the same name to achieve the concept of compile-time polymorphism in Java. // Java Example: Compile Time Polymorphism public class Main { // method to add two integers public int addition(int x, int y) { return x + y7 } 7/ method to add three integers public int addition(int x, int y, int 2) ( return x + y +z } // method to add two doubles public double addition(double x, double y) { return x + y? } // Main method public static void main(String[] args) { // Creating an object of the Main method Main number = new Main(); // calling the overloaded methods int resl = number.addition(444, 555) system. out.printIn ("Addition of two integers: "+ resl); int res2 = number.addition(333, 444, 555); system. out .print1n ("Addition of three integers: " + res2); double res3 = number.addition(10.15, 20.22) System. out .println ("Addition of two doubles: “ + res3); Run Time Polymorphism Run time polymorphism is also known as dynamic method dispatch and it is implemented by the method overriding. Example 8: Consider the following as an example // Java Example: Run Time Polymorphism class Vehicle { public void displayInfo() { System.out.print1n("Some vehicles are there."); Pg. 25 / ; parc ' class Car extends Vehicle ( // Method overriding @override public void displayInfo() { System.out.println("I have a Car."); } } class Bike extends Vehicle { // Method overriding @override public void displayInfo() | System.out.println("I have a Bike."); } } public class Main { public static void main(String[] args) { Vehicle vl = new Car(); // Upcasting Vehicle v2 = new Bike(); // Upcasting // Calling the overridden displayInfo() method of Car class vl.displayInfo(); // Calling the overridden displayInfo() method of Bike class v2.displayInfo(); Pg. 26

You might also like