Download presentation
Presentation is loading. Please wait.
2
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:
3
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.
4
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);
5
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 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);
6
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
7
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?
8
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.
9
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;
10
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;
11
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)
12
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; }
13
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
14
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.
15
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 {......}
16
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());
17
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
18
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?
19
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();
20
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?
21
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
22
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?
23
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");
24
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?
25
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);
26
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
27
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
28
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?
29
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");
30
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…
31
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
32
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
33
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
34
Protected: WORD OF THE DAY
All subclasses (derived classes) have access Everything else doesn’t.
35
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…
36
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;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.