Objects in other classes:

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Inheritance Writing and using Classes effectively.
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Written by: Dr. JJ Shepherd
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
These are the inheritance slides. They are slides just like all the other AP CS slides. But they are unique in that they all talk about inheritance.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Overloading vs. Overriding b Don't confuse the concepts of overloading and overriding b Overloading deals with multiple methods in the same class with.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
UML Basics & Access Modifier
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Intro to OOP with Java, C. Thomas Wu
CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design.
Inheritance. Inheritance Early programmers often wrote code very similar to existing code Example: A human resources system might handle different types.
What is inheritance? It is the ability to create a new class from an existing class.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Inheritance, Abstract & Interface Pepper With help from and
Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions. Avoiding duplication and redundancy.
Topic 4 Inheritance.
MIT AITI 2004 – Lecture 12 Inheritance. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits.
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
Inheritance  Inheritance is a fundamental object-oriented technique  it enhances software design and promotes reuse  We will focus on:  deriving new.
Inheritance Notes Chapter 6 1. Inheritance  you know a lot about an object by knowing its class  for example what is a Komondor? 2
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
COT int[] x = {3,7,2,4,1}; int[] y = {5,8,6,9}; x = y; x[2] = 0; for (int k: y) { System.out.print(k + " "); }
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
CS1101 Group1 Discussion 6 Lek Hsiang Hui comp.nus.edu.sg
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
Topics Instance variables, set and get methods Encapsulation
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
Remember this: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; // of type Animal an_arr[1] = a_dog ; //of type Dog an_arr[2] = a_wolf; // of type Wolf.
INTRODUCTION Java is a true OO language the underlying structure of all Java programs is classes. Everything must be encapsulated in a class that defines.
Inheritance.
Modern Programming Tools And Techniques-I
Classes and Objects Introduced
Inheritance ITI1121 Nour El Kadri.
Classes and Objects in Java
Chapter 5 Hierarchies IS-A associations superclasses subclasses
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
CS 302 Week 11 Jim Williams, PhD.
CS Week 13 Jim Williams, PhD.
More on Classes & Arrays
CSC 113 Tutorial QUIZ I.
CS1316: Representing Structure and Behavior
Extending Classes.
CS1316: Representing Structure and Behavior
Inheritance.
انجمن جاواکاپ تقدیم می‌کند دوره برنامه‌نويسی جاوا
Basics of OOP A class is the blueprint of an object.
CSE 142 Lecture Notes Inheritance, Interfaces, and Polymorphism
Chapter 11 Inheritance and Polymorphism
More on Creating Classes
C++ Programming CLASS This pointer Static Class Friend Class
CS 200 More Classes Jim Williams, PhD.
Chapter 11 Inheritance and Polymorphism Part 1
Barb Ericson Georgia Institute of Technology Oct 2005
Visibilities and Static-ness
Topics OOP Review Inheritance Review Abstract Classes
CIS 110: Introduction to computer programming
CS 240 – Advanced Programming Concepts
Presentation transcript:

Objects in other classes: Create a class for a card: public class Card { public int num; public String suit; public Card(int n, String s) { num = n; suit = s; } Now Create a class for a deck of card objects:

public class Deck { public Card[] deck; public Deck() { Card[] arr = new Card[52]; String[] suits = {"Club","Spade","Diamond","Heart"}; int index = 0; for (String s: suits) { for (int i = 1; i <= 13; i++) { arr[index] = new Card(i,s); index++; } public String toString() { String str=""; for (Card i: deck) { str += i.num + i.suit + " "; return(str); So far so good. What if we wanted to create a game that has a deckofcards field that is a Deck object. The game generates a random card from the deck and prints it out.

Create a game that has a deckofcards field that is a Deck object Create a game that has a deckofcards field that is a Deck object. The game generates and prints out a random card. import java.util.Random; public class CardGame { private Deck deckofcards; public CardGame() { deckofcards = new Deck(); } public void printRandomCardNum() { Random r= new Random(); int x = r.nextInt( ); int x = r.nextInt(deckofcards.deck.length); System.out.println( ); System.out.println(deckofcards.deck[x].num);

What does this do? public boolean Check2() { int s1 = 0; int prev = -1; for (int i = 0; i < mat.length; i++) { s1 = 0; s2 = 0; for (int j = 0; j < mat.length; j++){ s1 += mat[i][j]; s2 += mat[j][i]; if (i == j) { s3 += mat[i][j]; } if (j == mat.length - 1 - i){ s4 += mat[i][j]; if (s1 != s2) { return(s1 == s2); else if ((prev != -1) && (s1 != prev)) { return(false); else { prev = s1; return (s1 == s2) &&(s1 == prev) && (s1 == s3) && (s1 == s4); public boolean Check1() { int s1 = 0; int s2 = 0; int prev = -1; for (int i = 0; i < mat.length; i++) { s1 = 0; s2 = 0; for (int j = 0; j < mat.length; j++){ s1 += mat[i][j]; s2 += mat[j][i]; } if (s1 != s2) { return(s1 == s2); else if ((prev != -1) && (s1 != prev)) { return(false); else { prev = s1; return (s1 == s2) &&(s1 == prev);

Composition, Inheritance, and polymorphism Composition: defining a new class that is composed of other classes Student class was composed of the Course class Deck class was composed of the Card class CardGame was composed of Deck class (composed of Card class) Note that this is NOT inheritance. Inheritance: deriving a new class based on an existing class, with modifications or extensions. Polymorphism – lets us redefine methods in classes derived from other classes

this. -a reference to the current object this -a reference to the current object - the object whose method or constructor is being called. What if we had: public class Card { public int num; // why are these public? public String suit; public Card(int num, String suit) { num = num; suit = suit; } How can you tell which num is which, and which suit is which?

this public class Card { public int num; // why are these public? public String suit; public Card(int num, String suit) { this.num = num; this.suit = suit; } Now we know that this.num refers to the field of the class Card, and num refers to the input parameter.

this – with constructors Sometimes a constructor initializes a lot of fields. With different versions of the constructor, coding all the initializations gets tedious. We could use this to call the constructor, e.g., public class Rectangle{ private int x; private int y; private int width; private int height; public Rectangle() { this(0,0,1,1); } public Rectangle(int width, int height) { this(0,0,width,height); public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height;

public class Neighbor { int housenum; String streetname; Neighbor leftneighbor; Neighbor rightneighbor; public Neighbor(int housenum, String streetname) { //constructor 1 this(housenum,streetname,null,null); } public Neighbor(int housenum, String streetname, Neighbor leftneighbor) { // constructor 2 this(housenum,streetname,leftneighbor,null); public Neighbor(int housenum, String streetname, Neighbor leftneighbor, Neighbor rightneighbor) { //constructor 3 this.housenum = housenum; this.streetname = streetname; this.leftneighbor = leftneighbor; this.rightneighbor = rightneighbor; public Neighbor makeright() { // If we’re making a right neighbor, then what is that’s left neighbor? Neighbor right = new Neighbor(housenum + 2, streetname, this, null); return right; public Neighbor makeleft() { Neighbor left = new Neighbor(housenum - 2, streetname, null, this); return left;

Try: Write a class for a parent (maybe name,phonenumber?) if you are a parent, you must have a child Write a class for a child (maybe gender, name, age?) If you are a child, you must have a parent Now in the parent class, write a method that creates a child (use this)

public class Parent { int phonenum; String firstname; String lastname; char gender; Child child; public Parent(int phonenum, String first, String last, char gender ) { this.phonenum = phonenum; this.firstname = first; this.lastname = last; this.gender = gender; this.child = null; } public void makeChild() { Random r = new Random(); int x = r.nextInt(2); if (x == 0) { String first = JOptionPane.showInputDialog("What is the boy's name?"); child = new Child(first,lastname,"boy", 0, this); else { String first = JOptionPane.showInputDialog("What is the girl's name?"); child = new Child(first,lastname,"girl", 0, this); public class Child { String first; String last; String gender; int age; Parent parent; public Child(String f, String l, String gen, int age, Parent p) { this.first = f; this.last = l; this.gender = gen; this.age = age; this.parent = p; }

Composition, Inheritance, and polymorphism Composition: defining a new class that is composed of other classes Inheritance: deriving a new class based on an existing class, with modifications or extensions. Polymorphism – lets us redefine methods in classes derived from other classes

Inheritence Put classes into a hierarchy derive a new class based on an existing class with modifications or extensions (or why bother?). Avoiding duplication and redundancy Classes in the lower hierarchy is called a subclass (or derived, child, extended class). A class in the upper hierarchy is called a superclass (or base, parent class). Place all common variables and methods in the superclass Place specialized variables and methods in the subclasses redundancy reduced as common variables and methods are not repeated in all the subclasses.

In java, you use the word “extends” in the class definition to indicate a class is a subclass of another class, e.g., class Goalkeeper extends SoccerPlayer {......} class ChemStudent extends Student {.....} class Cylinder extends Circle {......}

public class Circle { private double radius; private double circumference; private double area; public Circle() { this(3.1); } public Circle(double rad) { radius = rad; circumference = getCirc(); area = getArea(); public double getRad() { return radius; public void setRad(double rad) { public double getCirc() { return (2.0 *radius * Math.PI); public double getArea() { return(radius * radius * Math.PI); public class Cylinder extends Circle { private double height; // Private field for only Cylinder objects public Cylinder(double radius, double h) { // Constructor super(radius); // invoke superclass' constructor height = h; } public Cylinder(double h) { super(); public double getHeight() { return height; public void setHeight(double h) { public double getVolume() { return getArea()*height; // Use Circle's getArea() public static void main(String[] args) { Circle x = new Circle(4.2); System.out.format("Circle Area: %5.2f\n", x.getArea()); System.out.format("Circle Circumference: %5.2f\n",x.getCirc()); Cylinder y = new Cylinder(3.0, 2.0); System.out.format("Cylinder Area: %5.2f\n",y.getArea()); System.out.format("Cylinder Circumference: %5.2f\n",y.getCirc()); System.out.format("Cylinder Volume: %5.2f\n",y.getVolume());

public static void main(String[] args) { Circle x = new Circle(4 public static void main(String[] args) { Circle x = new Circle(4.2); System.out.format("Circle Area: %5.2f\n", x.getArea()); System.out.format("Circle Circumference: %5.2f\n",x.getCirc()); Cylinder y = new Cylinder(3.0, 2.0); System.out.format("Cylinder Area: %5.2f\n",y.getArea()); System.out.format("Cylinder Circumference: %5.2f\n",y.getCirc()); System.out.format("Cylinder Volume: %5.2f\n",y.getVolume()); } Circle Area: 55.42 Circle Circumference: 26.39 Cylinder Area: 28.27 Cylinder Circumference: 18.85 Cylinder Volume: 56.55

What fields and methods are part of an_x? public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = false; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; public void sleep() { System.out.println(“Snore Snore"); public void talk() { System.out.println(“talking"); public class Dog extends Animal { public String breed; public Dog(){ super(); breed = “Mutt” public Dog(String name, String breed) { this(true,name,breed); public Dog(boolean pet, String name, String breed) { super(pet, name); this.breed = breed; public void move() { System.out.println("Frolicking forward"); public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); System.out.println(an_x.name); System.out.println(an_x.isaPet); an_x.sleep(); an_x.talk(); Dog a_dog = new Dog("Spot“,”pug”); System.out.println(a_dog.name); System.out.println(a_dog.isaPet); System.out.println(a_dog.breed); a_dog.sleep(); a_dog.talk(); a_dog.move(); } What fields and methods are part of an_x? What fields and methods are part of a_dog?

Do you see a problem? class A { private int f; class B extends A { public A(int x) { f = x; } class B extends A { public B() { class C { public static void main(String[] args) { B b = new B();

What methods and fields does a_dog have? public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; public void sleep() { System.out.println("Animal is sleeping"); public void talk() { System.out.println("talking"); public class Dog extends Animal { public String breed; public Dog(){ super(); breed = “Mutt” public Dog(String name, String breed) { this(true,name,breed); public Dog(boolean pet, String name, String breed) { super(pet, name); this.breed = breed; public void move() { System.out.println("Frolicking forward"); System.out.println(“bark bark"); public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); System.out.println(an_x.name); System.out.println(an_x.isaPet); an_x.sleep(); an_x.talk(); // what does this line do? Dog a_dog = new Dog("Spot“,”pug”); System.out.println(a_dog.name); System.out.println(a_dog.isaPet); System.out.println(a_dog.breed); a_dog.sleep(); a_dog.talk(); // what does this line do? a_dog.move(); } What methods and fields does a_dog have? What happens when a_dog.talk() is executed?

Overriding! Word of the Day! When in a subclass you write a method that overrides a method with the same name in its parent class. In essence, you’ve got a default method in the superclass And then you have a more specific (and accurate) method belonging to the subclass Every subclass can have its own default method that overrides the superclass’s method

public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; public void sleep() { System.out.println(“Snore Snore"); public void talk() { System.out.println("talking"); public class Dog extends Animal { public Dog(){ super(); public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public void move() { System.out.println("Frolicking forward"); System.out.println("bark bark"); public class Wolf extends Dog { public Wolf(){ super(false,"noName"); } public void move() { System.out.println("running intently"); public void stalk() { System.out.println("stalking my prey"); public void talk() { System.out.println("howl"); super.talk(); public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); // what methods and fields are available to an_x? Dog a_dog = new Dog("Spot"); // what methods and fields are available to a_dog? Wolf a_wolf = new Wolf(); // what methods and fields are available to a_wolf?

public class Wolf extends Dog { public Wolf(){ super(false,"noName“, “wolf”); } public void move() { System.out.println("running intently"); public void stalk() { System.out.println("stalking my prey"); public void talk() { System.out.println("howl"); super.talk(); public class mainAnimal { public static void main(String[] args) { Animal an_x = new Animal(); System.out.println(an_x.name); System.out.println(an_x.isaPet); an_x.sleep(); an_x.talk(); Dog a_dog = new Dog("Spot"); System.out.println(a_dog.name); System.out.println(a_dog.isaPet); a_dog.sleep(); a_dog.talk(); a_dog.move(); Wolf a_wolf = new Wolf(); System.out.println(a_wolf.name); System.out.println(a_wolf.isaPet); a_wolf.sleep(); a_wolf.talk(); a_wolf.move(); a_wolf.stalk(); public class Animal { public boolean isaPet; public String name; public Animal() { isaPet = true; name = "Fred"; } public Animal(boolean pet, String name) { isaPet = pet; this.name = name; public void sleep() { System.out.println("Animal is sleeping"); public void talk() { System.out.println("talking"); public class Dog extends Animal { public String breed; public Dog(){ super(); breed = “Mutt”; public Dog(String name) { super(true, name); public Dog(boolean pet, String name, String breed) { super(pet, name); this.reed = breed; public void move() { System.out.println("Frolicking forward"); System.out.println("bark bark");

Coolness: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; // of type Animal an_arr[1] = a_dog ; //of type Dog an_arr[2] = a_wolf; // of type Wolf for (int i = 0; i < 3; i++) { an_arr[i].talk(); if (an_arr[i].isaPet) { System.out.println(an_arr[i].name); } // what gets printed? // could I do an_arr[i].breed? (breed is a field in the dog class) // can I do an_arr[1].breed?

Only methods and fields in superclass can be accessed automatically: Animal[] an_arr = new Animal[3]; an_arr[0]= an_x; an_arr[1] = a_dog; an_arr[2] = a_wolf; for (int i = 0; i < 3; i++) { an_arr[i].talk(); if (an_arr[i].isaPet) { System.out.println(an_arr[i].name); } Dog tempd = (Dog)an_arr[1]; System.out.println(tempd.breed);

Overriding What is the output? twang public class Musician { public void play() { System.out.println(“silence”); } public class Drummer extends Musician { System.out.println(“boom boom”); public class Guitarist extends Musician { System.out.println(“twang”); ... Musician musician = new Guitarist(); musician.play(); What is the output? twang

Overriding What is the output? twang silence boom boom public class Musician { public void play() { System.out.println(“silence”); } public class Drummer extends Musician { System.out.println(“boom boom”); public class Guitarist extends Musician { System.out.println(“twang”); super.play(); ... Musician musician = new Guitarist(); musician.play(); musician = new Drummer(); What is the output? twang silence boom boom

Will this work? How can we fix this? … Wolf x = new Wolf(); public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public void move() { System.out.println("Going forward"); public void talk() { System.out.println("bark bark"); public class Wolf extends Dog { public Wolf(){ super(false,"noName",true); } public void move() { System.out.println("running intently"); public void stalk() { System.out.println("stalking my prey"); public void talk() { System.out.println("howl"); super.talk(); … Wolf x = new Wolf(); public class Animal { public boolean isaPet; public String name; public boolean isaWolf; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); public Animal(boolean pet, String name, boolean isawolf) { isaPet = pet; this.name = name; this.isaWolf = isawolf; public void sleep() { System.out.println("Animal is sleeping"); public void talk() { System.out.println("talking"); How can we fix this?

public class Wolf extends Dog { public Wolf(){ super(false,"noName",true); } public void move() { System.out.println("running intently"); public void stalk() { System.out.println("stalking my prey"); public void talk() { System.out.println("howl"); super.talk(); … Wolf x = new Wolf(); public class Animal { public boolean isaPet; public String name; public boolean isaWolf; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); public Animal(boolean pet, String name, boolean isawolf) { isaPet = pet; this.name = name; this.isaWolf = isawolf; public void sleep() { System.out.println("Animal is sleeping"); public void talk() { System.out.println("talking"); public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public Dog(boolean pet, String name,boolean isawolf) { super(pet, name,isawolf); public void move() { System.out.println("Going forward"); public void talk() { System.out.println("bark bark");

Public/Private and inheritance Anything in the superclass that is declared public is available to all subclasses (and everything else) Private – only the superclass has access to it Subclasses don’t have access We need something that will allow the subclasses to have access to the elements in the superclass, while still protecting these elements from being manipulated by other code/classes Hold that thought…

public class Animal { public boolean isaPet; public String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); public void talk() { System.out.println("talking"); public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public void talk() { System.out.println(name+“ says bark bark"); This works

This doesn’t work – use a getter public class Animal { public boolean isaPet; private String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); public void talk() { System.out.println("talking"); public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public void talk() { System.out.println(name+“ says bark bark"); This doesn’t work – use a getter

public class Animal { public boolean isaPet; private String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); public String getName() { return(name); public void talk() { System.out.println("talking"); public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public void talk() { System.out.println(getName()+“ says bark bark"); This works

Protected: WORD OF THE DAY All subclasses (derived classes) have access Everything else doesn’t.

Protected can be accessed in Dog Definition not outside… public class Animal { protected boolean isaPet; protected String name; public Animal() { this(true,"Fred",false); } public Animal(boolean pet, String name) { this(pet,name,false); public String getName() { return(name); public void talk() { System.out.println("talking"); public class Dog extends Animal { boolean isaDog = true; public Dog(){ super(); } public Dog(String name) { super(true, name); public Dog(boolean pet, String name) { super(pet, name); public void talk() { System.out.println(name+“ says bark bark"); Dog d = new Dog(“Fido”); System.out.println(d.name); // won’t work d.talk(); Protected can be accessed in Dog Definition not outside…

How many problems do you see? public class Circle { double radius; public Circle(double radius) { radius = radius; } public double getRadius() { return radius; public double getArea() { return radius * radius * Math.PI; public class B extends Circle { double length; public B(double radius, double length) { Circle(radius); return getArea() * length;