Java Classes, Inheritance, and Interfaces
|
|
- Laureen Ray
- 5 years ago
- Views:
Transcription
1 Java Classes, Inheritance, and Interfaces Introduction Classes are a foundational element in Java. Everything in Java is contained in a class. Classes are used to create Objects which contain the functionality of the program. The basic concept behind classes is that a Class is like a cookie-cutter which can be used to stamp out objects. Building a Java program consists of creating Classes, relationships between Classes, and with these classes, creating Objects. Another way to think about Classes is that Classes have an External structure (or shape) and an Internal structure. Classes present a Public view to other classes and objects and have an internal structure which is how the class actually works. The external structure can be connected to the internal structure in various ways. Classes and Objects A class is a programming structure which consists of Properties and Methods. A Property is a data items (which can be a basic data type such as a number, character, string, Boolean, etc) or which can be an object defined by another class. A Method is a function. Both the Properties and the Methods makeup the Internal and External structure of a class. In Java classes are defined using the class statement: class Monster { private String name; private int health; private int power; private double gold; private boolean hasweapon; private int[] weapons; public Monster() { name = "Monster"; health = 100; power = 100; gold = 0.0; hasweapon = false; In this case, we have a class named Monster that has a set of Properties (the variables declared under the class). This class also has a constructor named Monster(), which is the name of the class. This constructor sets the default values for the properties. When creating a class you will typically include the following elements: A. Properties which are declared as private B. One or more Constructor methods which will be automatically called when an object of this class is created. C. Accessor and Mutator methods which are used to get and set the properties. D. Overloaded methods for equals and hashcode. Once you have a class, you can create Objects using the class name. If the class has a defined Constructor method then the method is called when the object is created. For example, if you had the Monster class you would use it to create various Monster objects: Monster golom1 = new Monster(); Monster collmonster[] = new Monster[10]; collmonster[0] = new Monster(); collmonster[1] = new Monster(); In this example, the Monster class is used to create an object named golom1 and used to create an array of Monsters.
2 Basically, the Monster class can be used just like any other data type such as int or double. The list of items you should create when you create a class includes constructor, accessor, mutator, equals, and hashcode methods. Since these are so commonly done, Eclipse can be used to automatically create these methods for you once you have created a class. 1. Start Eclipse. 2. Create a new Java project named GameCharacters. 3. Right click this project and choose New Class. 4. For the Package Name use GameCharactes and for the Class name use Monster. Click Finish when done. 5. Inside the Monster class enter the following Properties: private String name; private int idnumber; private int health; private int power; private double gold; private boolean hasweapon; private int[] weapons; The values for this class include the name of the monster, an idnumber which will uniquely identify the monster, and values for health, power, gold, and weapons status. It also includes an array which can hold weapon id values.
3 6. Right click inside the class (between the { symbols) and choose Source. You see the code Source options: The options on this menu allow you to quickly create methods for your class. The options include: E. Generate Getters and Setters this will create methods to get and set properties. F. Generate hashcode() and equals() this will create methods that override the hashcode method and the equals method. G. Generate tostring() this will create a method to override the tostring() class. H. Generate Constructor using Fields this allows you to create a constructor method using some of the fields in your class if you want to initialize the class with values. Properties can be read and write or read-only. A read-only property must be set through the Constructor and have a getter method but cannot be changed. The terms getters and setters refer to simple methods that allow the internal class properties to be set with a value (setters) and to retrieve values (getters). All properties will be set to private so that any access must be done through methods. This protects the internal values of the class. If objects created from this class will have an identity value so we can tell objects apart, then we need to override the hashcode() and equals() methods. The identity value must be able to uniquely identify the object. In this case, the idnumber field will be the identify field. We need to make this property read-only and to set the value through a constructor.
4 7. In the Source menu choose Generate Constructor using Fields. You see a dialog box listing all the properties in this class. You only want to choose the idnumber field. 8. Uncheck everything except the idnumber field and click the Generate constructor comments option and check the Omit call to default constructor super() field. 9. Click OK to generate the constructor. You will next create getters and setters for all properties. However, for the idnumber property you will only create a getter because this is a read-only property. 10. Right click in the class, choose Source, and choose Generate Getters and Setters.
5 11. Modify the dialog box so it looks like the figure. You will generate getters and setters for all properties but will only generate a getter for idnumber. You will also generate comments for these methods. 12. Click OK to generate the code. Finally, you will override the tostring method and the hashcode and equals methods. The tostring method is a utility method which, when called, returns a string id value of your object. This can be used for log files, debugging, etc. One way to create this method is by converting all the class properties into string values. 13. Right click in the class, choose Source, and choose Generate tostring() method. You see the tostring options:
6 14. Click OK to accept the default values. You will next generate the hashcode and equals methods. These are using when comparing objects or when you use the Java collection classes to manage objects. Typically, you want to make sure that each object has a unique ID value (in this case it will be the idnumber property). 15. Right click in the class, choose Source, and choose Generate hashcode and equals. You see the dialog box for generating hashcode and equals. You will use the name field and the idnumber field to generate a unique ID. 16. Unselect everything except the name and idnumber fields. 17. Make sure Generate method comments is selected and then click OK. You see the methods overriding hashcode and equals. The equals method will return true or false if two objects are the same and the hashcode method
7 will be used by collection classes to identify the object. For example, suppose we create the equals() method and then create two objects of type Monster: Monster a = new Monster(12345); a.setname( Frank ); Monster b = new Monster(87899); b.setname( Joe ); if( a.equals(b) ) System.out.println( Same Monster ); else System.out.println( Not the same Monster ); Lets fill out some more code for our monster class. These methods refer to a GameCharacter class which does not yet exist. 18. Click inside the class and enter the following lines of code: // Monster actions public GameCharacter fight(gamecharacter c) { c.sethealth( c.gethealth()-this.power); return c; public boolean areyoudead() { if(this.health<=0) return true; else Inheritance The idea behind inheritance is that many classes are variations on other classes and this fact should be used to simplify and make more efficient class design. The idea of inheritance is that a new class can be created by extending an existing class, keeping all the methods that will be used in the new class, and adding the unique methods for the new class. In order to better discuss inheritance it is useful to use some common terminology. A Base class, which is also called a Parent class, is the class which will be used as the basis of the derived class (also called the Child class). Base Class inherit from Derived class Parent Class inherit from Child Class Some of the rules in inheritance are defined by how the properties and methods in the base class are set: Access Levels Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N
8 no modifier Y Y N N private Y N N N For example, from within the same class anything with these four modifiers is accessible. However, a derived class cannot access private and no modifier options and only public and protected. There are a number of ways that you can implement inheritance from a Base class. These include: A. Add new methods to the Derived class while reusing all the public/protected methods from the Base class. B. The Derived class overrides a public/protected method from the base class C. The Base class includes one or more abstract methods which require the Derived class to override these methods and prevent the Base class from being used to create objects. In method A the base and derived classes can be used to create objects. The Derived class is just a special case of the Base class and includes its own special methods. For example, suppose we want to create a new Monster class called a BossMonster. This will have all the methods and properties of the Base class Monster but will have a new ability named Magic in which the monster can throw magic spells at the player s character. Since this is a new property the derived class needs to add the property, add getters and setters for the property, and add a method that is used to cast a spell on another game character. 1. Make sure your Monster class has been saved (there will be an error because the GameCharacter class has not been created). 2. Right click your Project and choose New and choose Class. You will let Eclipse handle setting up the new class. 3. In the New Class dialog box, for the Name enter BossMonster. 4. For the Superclass name type Monster. This is the Base class we wish to inherit from. 5. Click the check boxes for Generate Comments and for Constructors for superclass. 6. Click Finish. You see your class has been created and the constructor for the super class automatically added. public class BossMonster extends Monster { idnumber public BossMonster(int idnumber) { super(idnumber); // TODO Auto-generated constructor stub The extends word indicates that this class is extended from the base class. Objects of type BossMonster have access to all the public methods and properties of the base class. For example: BossMonster m = new BossMonster(1234); m.sethealth(100); int x = m.gethealth();
9 You next want to add the Magic property which will represent a number of magical elements that can be used in battle. 7. Edit your class so it looks like: public class BossMonster extends Monster { private int MagicForce; idnumber public BossMonster(int idnumber) { super(idnumber); // TODO Auto-generated constructor stub We will next let Eclipse create the getter and setter: 8. Right click in this class, choose Source, and select Generate Getters and Setters. 9. Click the MagicForce element and then click OK. The getters and setters are now created. All of the other public methods in the base class are still available to BossMonster objects. Another way to use inheritance is to override methods. A Derived class automatically gets access to all public/protected methods from the Base class. However, there are times when you want to extend one of the Base class methods. In this case the base class method: public boolean areyoudead() { if(this.health<=0) return true; else returns true if the health of the monster is gone. However, for BossMonsters both the health and the magic must both be zero. You want to override this method. 10. Right-click in the BossMonster class and choose Source. 11. Choose Overide/Implement methods. This brings up a dialog box that shows all the methods in the base class. 12. Choose the areyoudead() method and click OK. You see the code added to your public boolean areyoudead() { // TODO Auto-generated method stub return super.areyoudead();
10 The is not a Java command but used to identify overridden methods. Notice that all the default method does is return the results of the Base class method areyoudead(). What we want to do is add in a check to see if the MagicForce value is also <= zero. This can be done by using an inline IF statement and combining this with the super.areyoudead() method (which returns a Boolean). 13. Edit this code so it looks like: public boolean areyoudead() { // TODO Auto-generated method stub return (super.areyoudead()&&(this.getmagicforce()<=0?true:false)); Look at this statement. The code: (this.getmagicforce() <=0? true: false) will call the getter and get the magic force value, compare it to zero, and if it is less than or equal to zero will return true, else will return false. The call to the Base class method is: super.areyoudead() and this will return true if the health is gone and false if there is some health. Combining these two Boolean checks together using the && statement looks like: true && true gives true false && true gives false true && false gives false false && false gives false The && operator returns a Boolean value by taking the two conditions and performing a Boolean operation.
11 The two classes look like: package GameCharacters; import java.util.arrays; public class Monster { private String name; private int idnumber; private int health; private int power; private double gold; private boolean hasweapon; private int[] weapons; idnumber public Monster(int idnumber) {this.idnumber = idnumber; the name public String getname() {return name; the idnumber public int getidnumber() {return idnumber; the health public int gethealth() {return health; the power public int getpower() {return power; the gold public double getgold() {return gold; the hasweapon public boolean ishasweapon() {return hasweapon; the weapons public int[] getweapons() {return weapons; name the name to set public void setname(string name) {this.name = name; health the health to set public void sethealth(int health) {this.health = health; power the power to set public void setpower(int power) {this.power = power; gold the gold to set
12 public void setgold(double gold) {this.gold = gold; hasweapon the hasweapon to set public void sethasweapon(boolean hasweapon) {this.hasweapon = hasweapon; weapons the weapons to set public void setweapons(int[] weapons) {this.weapons = weapons; /* (non-javadoc) public String tostring() { return "Monster [name=" + name + ", idnumber=" + idnumber + ", health=" + health + ", power=" + power + ", gold=" + gold + ", hasweapon=" + hasweapon + ", weapons=" + Arrays.toString(weapons) + "]"; /* (non-javadoc) public int hashcode() { final int prime = 31; int result = 1; result = prime * result + idnumber; result = prime * result + ((name == null)? 0 : name.hashcode()); return result; /* (non-javadoc) public boolean equals(object obj) { if (this == obj) return true; if (obj == null) if (getclass()!= obj.getclass()) Monster other = (Monster) obj; if (idnumber!= other.idnumber) if (name == null) { if (other.name!= null) else if (!name.equals(other.name)) return true; // Monster actions public GameCharacter fight(gamecharacter c) { c.sethealth( c.gethealth()-this.power); return c; public boolean areyoudead() { if(this.health<=0) return true;
13 else * package GameCharacters; dcraig * public class BossMonster extends Monster { private int MagicForce; idnumber public BossMonster(int idnumber) { super(idnumber); // TODO Auto-generated constructor stub the magicforce public int getmagicforce() { return MagicForce; magicforce the magicforce to set public void setmagicforce(int magicforce) { MagicForce = magicforce; /* (non-javadoc) public boolean areyoudead() { // TODO Auto-generated method stub return (super.areyoudead()&&(this.getmagicforce()<=0?true:false)); You will notice that Eclipse automatically adds the before the class. This is a compile-time flag to tell the Java VM that this method overrides a method in the Base class. The other term, Overloading, is a bit different. If your method in the Derived class has different parameters or return type then you are Overload a base class method: Override same method signature as Base class but different implementation Overload different method signature from Base class and different implementation You also notice that the reserve term super is used to call methods from the base class.
14 The Inheritance relationship allows one class to be used as a pattern for another class, in this case the Monster class is used as a pattern for the BossMonster class. However, the Monster class can still be used to create objects. There are times when you only want a Base class used as a pattern but not have the ability to create base class objects. In this case you would declare the base class abstract which would prevent this class being used to create objects. public abstract class BaseMonster { by including the term abstract in the class declaration you are telling the compiler that this class cannot be used to create objects but it can still be used in inheritance relationships. public class Monster extends BaseMonster { All the methods defined in the base class are still implemented in the derived class. Using an abstract class to enforce consistency is useful, but there are often times when you want to make sure that all the classes inheriting from the Base class create a necessary set of methods. For example, suppose that all our varieties of Monsters must have a method for fighting, but that each monster fights in a different way. One type may fight with magic while another fights with hands. This fight() method must be defined for each monster. When inheriting from a base class, and to ensure that the method defined in the base class is overridden in the derived class, you can make the method abstract. public abstract class BaseMonster{ public abstract void Fight(); In this case both the class and the method must be declared with the abstract term. When a class inherits from this class it must override this abstract method and create its own method. public class Monster extends BaseMonster { public void Fight() { If the derived class does not implement the abstract method then the compiler flags an error. You can use override to create new methods with the same method signature as the base class, but this is no guarantee that the derived class will implement the method. By making the method Abstract you ensure that this method will be implemented.
15 For example, suppose we want all Monsters in the game to have the same basic functionality for power, health, name, and fighting.
Inheritance (Part 5) Odds and ends
Inheritance (Part 5) Odds and ends 1 Static Methods and Inheritance there is a significant difference between calling a static method and calling a non-static method when dealing with inheritance there
More informationMore about inheritance
Main concepts to be covered More about inheritance Exploring polymorphism method polymorphism static and dynamic type overriding dynamic method lookup protected access 4.1 The inheritance hierarchy Conflicting
More informationINHERITANCE. Spring 2019
INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose
More informationInheritance. Lecture 11 COP 3252 Summer May 25, 2017
Inheritance Lecture 11 COP 3252 Summer 2017 May 25, 2017 Subclasses and Superclasses Inheritance is a technique that allows one class to be derived from another. A derived class inherits all of the data
More informationDay 4. COMP1006/1406 Summer M. Jason Hinek Carleton University
Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information
More informationInheritance. Notes Chapter 6 and AJ Chapters 7 and 8
Inheritance Notes Chapter 6 and AJ Chapters 7 and 8 1 Inheritance you know a lot about an object by knowing its class for example what is a Komondor? http://en.wikipedia.org/wiki/file:komondor_delvin.jpg
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More informationPolymorphism. return a.doublevalue() + b.doublevalue();
Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces
More informationThe class Object. Lecture CS1122 Summer 2008
The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship
More informationCS-202 Introduction to Object Oriented Programming
CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction
More informationFundamental Java Methods
Object-oriented Programming Fundamental Java Methods Fundamental Java Methods These methods are frequently needed in Java classes. You can find a discussion of each one in Java textbooks, such as Big Java.
More informationCMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.
CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object
More informationInheritance. Transitivity
Inheritance Classes can be organized in a hierarchical structure based on the concept of inheritance Inheritance The property that instances of a sub-class can access both data and behavior associated
More informationDistributed Systems Recitation 1. Tamim Jabban
15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming
More informationIntroduction to Inheritance
Introduction to Inheritance James Brucker These slides cover only the basics of inheritance. What is Inheritance? One class incorporates all the attributes and behavior from another class -- it inherits
More informationAbstract Classes and Interfaces
Abstract Classes and Interfaces Reading: Reges and Stepp: 9.5 9.6 CSC216: Programming Concepts Sarah Heckman 1 Abstract Classes A Java class that cannot be instantiated, but instead serves as a superclass
More informationComputer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7
Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7 1 Problem Ralph owns the Trinidad Fruit Stand that sells its fruit on the street, and he wants to use a computer
More informationJava Fundamentals (II)
Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class
More informationObject Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming
Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in
More informationBig software. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance Big software software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues: getting
More informationDistributed Systems Recitation 1. Tamim Jabban
15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming
More informationChapter 5 Object-Oriented Programming
Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares
More informationCLASS DESIGN. Objectives MODULE 4
MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors
More informationSuper-Classes and sub-classes
Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an
More informationInformatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,
Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &
More informationContents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance
Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass
More informationLecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University
Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types
More informationENCAPSULATION AND POLYMORPHISM
MODULE 3 ENCAPSULATION AND POLYMORPHISM Objectives > After completing this lesson, you should be able to do the following: Use encapsulation in Java class design Model business problems using Java classes
More informationCREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed
CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?
More informationBasic Object-Oriented Concepts. 5-Oct-17
Basic Object-Oriented Concepts 5-Oct-17 Concept: An object has behaviors In old style programming, you had: data, which was completely passive functions, which could manipulate any data An object contains
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract
More informationCOE318 Lecture Notes Week 8 (Oct 24, 2011)
COE318 Software Systems Lecture Notes: Week 8 1 of 17 COE318 Lecture Notes Week 8 (Oct 24, 2011) Topics == vs..equals(...): A first look Casting Inheritance, interfaces, etc Introduction to Juni (unit
More informationChapter 4 Defining Classes I
Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the
More informationLecture 2: Java & Javadoc
Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block
More informationInformatik II (D-ITET) Tutorial 6
Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,
More informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationThe software crisis. code reuse: The practice of writing program code once and using it in many contexts.
Inheritance The software crisis software engineering: The practice of conceptualizing, designing, developing, documenting, and testing largescale computer programs. Large-scale projects face many issues:
More informationBinghamton University. CS-140 Fall Problem Solving. Creating a class from scratch
Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods
More informationDeclarations and Access Control SCJP tips
Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for
More informationC12a: The Object Superclass and Selected Methods
CISC 3115 TY3 C12a: The Object Superclass and Selected Methods Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/4/2018 CUNY Brooklyn College 1 Outline The Object class and
More informationRules and syntax for inheritance. The boring stuff
Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for
More informationName Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?
1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract
More informationCOMP 250. Lecture 32. polymorphism. Nov. 25, 2016
COMP 250 Lecture 32 polymorphism Nov. 25, 2016 1 Recall example from lecture 30 class String serialnumber Person owner void bark() {print woof } : my = new (); my.bark();?????? extends extends class void
More informationAdvanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II
Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic
More informationInformatik II Tutorial 6. Subho Shankar Basu
Informatik II Tutorial 6 Subho Shankar Basu subho.basu@inf.ethz.ch 06.04.2017 Overview Debriefing Exercise 5 Briefing Exercise 6 2 U05 Some Hints Variables & Methods beginwithlowercase, areverydescriptiveand
More informationProgramming Exercise 14: Inheritance and Polymorphism
Programming Exercise 14: Inheritance and Polymorphism Purpose: Gain experience in extending a base class and overriding some of its methods. Background readings from textbook: Liang, Sections 11.1-11.5.
More informationDay 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University
Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays
More informationCOMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code
COMPUTER SCIENCE DEPARTMENT PICNIC Welcome to the 2016-2017 Academic year! Meet your faculty, department staff, and fellow students in a social setting. Food and drink will be provided. When: Saturday,
More informationCOMP200 - Object Oriented Programming: Test One Duration - 60 minutes
COMP200 - Object Oriented Programming: Test One Duration - 60 minutes Study the following class and answer the questions that follow: package shapes3d; public class Circular3DShape { private double radius;
More informationChapter 15: Object Oriented Programming
Chapter 15: Object Oriented Programming Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey How do Software Developers use OOP? Defining classes to create objects UML diagrams to
More informationMore On inheritance. What you can do in subclass regarding methods:
More On inheritance What you can do in subclass regarding methods: The inherited methods can be used directly as they are. You can write a new static method in the subclass that has the same signature
More informationThe Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000
The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes
More informationMaking New instances of Classes
Making New instances of Classes NOTE: revised from previous version of Lecture04 New Operator Classes are user defined datatypes in OOP languages How do we make instances of these new datatypes? Using
More informationMethods Common to all Classes
Methods Common to all Classes 9-2-2013 OOP concepts Overloading vs. Overriding Use of this. and this(); use of super. and super() Methods common to all classes: tostring(), equals(), hashcode() HW#1 posted;
More informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 17 Inheritance Overview Problem: Can we create bigger classes from smaller ones without having to repeat information? Subclasses: a class inherits
More informationObject Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.
CMSC 131: Chapter 28 Final Review: What you learned this semester The Big Picture Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach. Java
More informationJava Magistère BFA
Java 101 - Magistère BFA Lesson 3: Object Oriented Programming in Java Stéphane Airiau Université Paris-Dauphine Lesson 3: Object Oriented Programming in Java (Stéphane Airiau) Java 1 Goal : Thou Shalt
More informationCS-140 Fall 2017 Test 2 Version A Nov. 29, 2017
CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : An interface defines the list of fields
More informationInheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L
Inheritance Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 9.4 1 Inheritance Inheritance allows a software developer to derive
More informationOverview of Eclipse Lectures. Module Road Map
Overview of Eclipse Lectures 1. Overview 2. Installing and Running 3. Building and Running Java Classes 4. Refactoring Lecture 2 5. Debugging 6. Testing with JUnit 7. Version Control with CVS 1 Module
More informationCS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun Announcements Project 1 is out! Due July 15 th. Check the course website. Reminder: the class newsgroup ucb.class.cs61b should
More informationCanonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering
CSC40232: SOFTWARE ENGINEERING Professor: Jane Cleland Huang Canonical Form sarec.nd.edu/courses/se2017 Department of Computer Science and Engineering Canonical Form Canonical form is a practice that conforms
More informationAP Computer Science Chapter 10 Implementing and Using Classes Study Guide
AP Computer Science Chapter 10 Implementing and Using Classes Study Guide 1. A class that uses a given class X is called a client of X. 2. Private features of a class can be directly accessed only within
More informationLecture 4: Extending Classes. Concept
Lecture 4: Extending Classes Concept Inheritance: you can create new classes that are built on existing classes. Through the way of inheritance, you can reuse the existing class s methods and fields, and
More informationCS18000: Problem Solving And Object-Oriented Programming
CS18000: Problem Solving And Object-Oriented Programming Data Abstraction: Inheritance 7 March 2011 Prof. Chris Clifton Data Abstraction Continued Abstract data type provides Well-defined interface Separation
More informationCmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects
CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationInheritance and Polymorphism
Object Oriented Programming Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. Al-Azhar University Website: eaymanelshenawy.wordpress.com Email : eaymanelshenawy@azhar.edu.eg
More informationPrinciples of Object Oriented Programming. Lecture 4
Principles of Object Oriented Programming Lecture 4 Object-Oriented Programming There are several concepts underlying OOP: Abstract Types (Classes) Encapsulation (or Information Hiding) Polymorphism Inheritance
More informationCOMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed
1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every
More informationCMSC 132: Object-Oriented Programming II. Inheritance
CMSC 132: Object-Oriented Programming II Inheritance 1 Mustang vs Model T Ford Mustang Ford Model T 2 Interior: Mustang vs Model T 3 Frame: Mustang vs Model T Mustang Model T 4 Compaq: old and new Price:
More informationCOE318 Lecture Notes Week 9 (Week of Oct 29, 2012)
COE318 Lecture Notes: Week 9 1 of 14 COE318 Lecture Notes Week 9 (Week of Oct 29, 2012) Topics The final keyword Inheritance and Polymorphism The final keyword Zoo: Version 1 This simple version models
More informationAP CS Unit 6: Inheritance Notes
AP CS Unit 6: Inheritance Notes Inheritance is an important feature of object-oriented languages. It allows the designer to create a new class based on another class. The new class inherits everything
More informationIBS Software Services Technical Interview Questions. Q1. What is the difference between declaration and definition?
IBS Software Services Technical Interview Questions Q1. What is the difference between declaration and definition? The declaration tells the compiler that at some later point we plan to present the definition
More informationCS 251 Intermediate Programming Inheritance
CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?
More information1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides
1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of
More informationObject-Oriented Concepts
JAC444 - Lecture 3 Object-Oriented Concepts Segment 2 Inheritance 1 Classes Segment 2 Inheritance In this segment you will be learning about: Inheritance Overriding Final Methods and Classes Implementing
More informationAgenda. Objects and classes Encapsulation and information hiding Documentation Packages
Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics
More informationInheritance (Part 2) Notes Chapter 6
Inheritance (Part 2) Notes Chapter 6 1 Object Dog extends Object Dog PureBreed extends Dog PureBreed Mix BloodHound Komondor... Komondor extends PureBreed 2 Implementing Inheritance suppose you want to
More informationToday. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.
Today Book-keeping Inheritance Subscribe to sipb-iap-java-students Interfaces Slides and code at http://sipb.mit.edu/iap/java/ The Object class Problem set 1 released 1 2 So far... Inheritance Basic objects,
More informationCSC207H: Software Design. Java + OOP. CSC207 Winter 2018
Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside
More information8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14
8.1 Inheritance superclass 8.1 Class Diagram for Words! Inheritance is a fundamental technique used to create and organize reusable classes! The child is- a more specific version of parent! The child inherits
More informationBoaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman )
My name is Ryan; I inherited the ship from the previous Dread Pirate Roberts, just as you will inherit it from me. The man I inherited it from is not the real Dread Pirate Roberts either. His name was
More informationINTERFACES. 24-Dec-10 INTERFACES VS. INHERITANCE. Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman ) Interfaces: Inheritance:
My name is Ryan; I inherited the ship from the previous Dread Pirate Roberts, just as you will inherit it from me. The man I inherited it from is not the real Dread Pirate Roberts either. His name was
More informationBinghamton University. CS-140 Fall Chapter 9. Inheritance
Chapter 9 Inheritance 1 Shapes Created class Point for (x,y) points Created classes: Rectangle, Circle, RightTriangle All have llc field All have dimensions, but different for each shape All have identical
More informationGoals for Today. CSE1030 Introduction to Computer Science II. CSE1030 Lecture #9. Review is-a versus has-a. Lecture #9 Inheritance I
CSE1030 Introduction to Computer Science II Lecture #9 Inheritance I Goals for Today Today we start discussing Inheritance (continued next lecture too) This is an important fundamental feature of Object
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationObject Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit
Object Oriented Programming Part 3 Writing Java with Eclipse and JUnit Today's Lecture Test Driven Development Review (TDD) Building up a class using TDD Adding a Class using Test Driven Development in
More informationCH. 2 OBJECT-ORIENTED PROGRAMMING
CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED
More informationCSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill
CSCI 136 Data Structures & Advanced Programming Lecture 3 Fall 2017 Instructors: Bill & Bill Administrative Details Lab today in TCL 216 (217a is available, too) Lab is due by 11pm Sunday Copy your folder
More informationInheritance. Exploring Polymorphism. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics
Inheritance Exploring Polymorphism Produced by: Mairead Meagher Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Lectures and Labs This weeks lectures and labs are based on
More informationTopic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.
Topic 5 Polymorphism " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code. 1 Polymorphism Another feature of OOP literally having many forms object variables in
More informationArgument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.
Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar
More informationChapter 9 Inheritance
Chapter 9 Inheritance I. Scott MacKenzie 1 Outline 2 1 What is Inheritance? Like parent/child relationships in life In Java, all classes except Object are child classes A child class inherits the attributes
More informationCompuScholar, Inc. 9th - 12th grades
CompuScholar, Inc. Alignment to the College Board AP Computer Science A Standards 9th - 12th grades AP Course Details: Course Title: Grade Level: Standards Link: AP Computer Science A 9th - 12th grades
More informationCS1150 Principles of Computer Science Objects and Classes
CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8
More informationVIRTUAL FUNCTIONS Chapter 10
1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions
More informationCMSC 132: Object-Oriented Programming II
CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation
More informationTopic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC
Topic 7: Inheritance Reading: JBD Sections 7.1-7.6 1 A Quick Review of Objects and Classes! An object is an abstraction that models some thing or process! Examples of objects:! Students, Teachers, Classes,
More information