SlideShare a Scribd company logo
Object-Oriented Programming and Java
Java Basic
Introducing Classes
• A template for multiple objects with similar features. Classes embody
all the features of a particular set of objects.
• A class is a reference type, which means that a variable of the class
type can reference an instance of the class.
• An object represents an entity in the real world that can be distinctly
identified.
• object is an instance(Creating) of a class(Data member +Method
member).
• A class library is a set of classes.
• Every Class is made up of two components: attributes and behavior.
– Attributes:state of an object (also known as its properties or attributes)
individual things differentiate one object from another and determine
appearance, state, data field(Table): object’s data fields, or other
qualities of that object.
– Behavior: (also known as its actions) what instances of that class do
when their internal state changes.
• Methods are functions defined inside classes that operate on instances of those
classes.
Chapter ii(oop)
• An object is an instance of a class. Default value= null
• You can create many instances of a class. Creating an instance is referred to as
instantiation.
• Box mybox; // declare reference to object//a variable of the class type can
reference an instance of the class
• mybox = new Box(); // allocate a Box object//assigns its reference to Box
• The dot operator links the name of the object with the name of an instance
variable.
• dot operator to access both the instance variables and the methods within an
object.
• references a data field in the object.
• invokes a method on the object
General form of class
Public class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
Circle:
radius: double
Circle(newRadius: double)
getArea(): double
TV:
channel: int
volumeLevel: int
on: boolean
+turnOn(): void
+turnOff(): void
+setChannel(newChannel: int): void
+setVolume(newVolumeLevel: int): void
+channelUp(): void
+channelDown(): void
+volumeUp(): void
+volumeDown(): void
public class Pet {
public int age;
float weight;
float height;
String color;
public void sleep(){
System.out.println(
"Good night, see you tomorrow");
}
public void eat(){
System.out.println(
"I’m so hungry…let me have a snack like nachos!");
}
public String say(String aWord){
String petResponse = "OK!! OK!! " +aWord;
return petResponse;
}
}
public class Test {
String make;
String color;
boolean engineState;
void startEngine()
{
if (engineState == true)
System.out.println("The engine is already on.");
else
{
engineState = true;
System.out.println("The engine is now on.");
}
}
void showAtts()
{
System.out.println("This motorcycle is a " + color + " " + make);
if (engineState == true)
System.out.println("The engine is on.");
else System.out.println("The engine is off.");
}
public static void main(String[] args)
{
Test m = new Test();
m.make = "Yamaha RZ350";
m.color = "yellow";
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("--------");
System.out.println("Starting engine...");
m.startEngine();
System.out.println("--------");
System.out.println("Calling showAtts...");
m.showAtts();
System.out.println("--------");
System.out.println("Starting engine...");
m.startEngine();
}
}
class Box {
double width;
double height;
double depth;
}
class TestOOP1 {
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
Box box2=new Box();
}
}
Method
type name(parameter-list) {
// body of method
}
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);}}
• c1 = c2, c1 points to the same object
• referenced by c2. The object previously referenced by c1 is no longer
useful and therefore is now known as garbage. Garbage occupies
memory space.
• object is no longer needed, you can explicitly assign null to a
reference variable for the object.
Garbage collection
• allocated by using the new operator
• Deallocation is called garbage collection.
objectName=null;
– The finalize( ) Method
protected void finalize( )
{
// finalization code here
}
Constructors• methods of a special type, known as constructors
• A constructor must have the same name as the class itself.
• It can be tedious to initialize all of the variables in a class each time an instance is created by
Method set.
• Constructors are invoked using the new operator when an object is created. Constructors
play the role of initializing objects.
• A constructor initializes an object immediately upon creation.
• look a little strange because they have no return type, not even void.
• Constructors are designed to perform initializing actions, such as initializing the data fields of
objects.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
Box mybox1 = new Box();
Box mybox2 = new Box();
Or
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box mybox1 = new Box(2,3,1);
Box mybox2 = new Box(2,4,1);
Overloading Constructors
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " +
vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " +
vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " +
vol);
}
}
The this Keyword
• be used inside any method to refer to the current object.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Overloading Methods
• two or more methods within the same class
that share the same name, as long as their
parameter declarations are different.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}}
Using Objects as Parameters
• Like passing an array, passing an object is actually passing the reference of the object.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
class Box {
double width;
double height;
double depth;
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons2 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " +
vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " +
vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}}
Returning Objectsclass Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "
+ ob2.a);}}
Array of object
• declares and creates an array of ten Circle objects:
– Circle[] circleArray = new Circle[10];
• To initialize the circleArray, you can use a for loop like this one:
for (int i = 0; i < circleArray.length; i++) {
circleArray[i] = new Circle();
}
• An array of objects is actually an array of reference
variables
• invoking circleArray[1].getArea() involves two levels of
referencing, as shown in Figure 8.18. circleArray references
the entire array. circleArray[1] references a Circle object.
• When an array of objects is created using the new
operator, each element in the array is a reference variable
with a default value of null.
Chapter ii(oop)
Chapter ii(oop)
Static Variables, Constants, and Methods
• Static variables store values for the variables in a
common memory location.
• Static methods can be called without creating an
instance of the class.
Chapter ii(oop)
Chapter ii(oop)
Introducing Access Control
• public specifier, then that member can be accessed by any other code.
This is not good for 2 reason
– 1. arbitrary value
– 2. class becomes difficult to maintain and vulnerable to bugs.
• private, then that member can only be accessed by other members of its
class. To prevent direct modifications of data fields, you should declare the
data fields private,using the private modifier. This is known as data field
encapsulation.
• protected applies only when inheritance is involved.
• Colloquially, a get method is referred to as a getter (or accessor), and a set
method is referred to as a setter (or mutator).
Chapter ii(oop)
Inheritance – a Fish is Also a Pet
• Object-oriented programming allows you to derive new
classes from existing classes called inheritance.
• best way to design these classes so to avoid redundancy
and make the system easy to comprehend and easy to
maintain?
• every person inherits some features from his or her
parents.
• behavior and attributes that are shared by many pets.
• pets are different - dogs bark, fish swim and do not make
sounds, parakeets talk better than dogs. But all of them
eat, sleep, have weight and height.
• Fish is a subclass of the class Pet or Pet as a template for
creating a class Fish.
class GeometricObject1 {
public String color = "white";
private boolean filled;
private java.util.Date dateCreated;
public GeometricObject1() {
dateCreated = new java.util.Date();}
public GeometricObject1(String Color, boolean filled)
{dateCreated = new java.util.Date();
this.color = color;
this.filled = filled;}
public String getColor() {
return color;}
public void setColor(String color) {
this.color = color;}
public boolean isFilled() {
return filled;}
public void setFilled(boolean filled) {
this.filled = filled;}
public java.util.Date getDateCreated() {
return dateCreated; }
public String toString() {
return "created on " + dateCreated + "ncolor: " +
color + " and filled: " + filled;}}
class Circle4 extends GeometricObject1 {
private double radius;
public Circle4() {}
public Circle4(double radius) {
this.radius = radius;
color=“red”;}
public Circle4(double radius, String color,
boolean filled) {
this.radius = radius;
setColor(color);
setFilled(filled); }
public double getRadius() {
return radius;}
public void setRadius(double radius) {
this.radius = radius; }
public double getArea() {
return radius * radius * Math.PI;}
public double getDiameter() {
return 2 * radius; }
public double getPerimeter() {
return 2 * radius * Math.PI; }
public void printCircle() {
System.out.println("The circle is created " + " and the
radius is " + radius); }
}
class Rectangle1 extends GeometricObject1 {
private double width;
private double height;
public Rectangle1() {}
public Rectangle1(double width, double height) {
this.width = width;
this.height = height;}
public Rectangle1(double width, double height,
String color,
boolean filled) {
this.width = width;
this.height = height;
setColor(color);
setFilled(filled);}
public double getWidth() {
return width;}
public void setWidth(double width) {
this.width = width; }
public double getHeight() {
return height; }
public void setHeight(double height) {
this.height = height; }
public double getArea() {
return width * height; }
public double getPerimeter() {
return 2 * (width + height);
} }
public class Test3 {
public static void main(String[] args) {
Circle4 circle = new Circle4(1);
System.out.println("A circle "+ circle.toString());
System.out.println("The radius is "+ circle.getRadius() );
System.out.println("The area is "+ circle.getArea());
System.out.println("The diameter is "+
circle.getDiameter());
Rectangle1 rectangle = new Rectangle1(2, 4);
System.out.println("nA rectangle "+
rectangle.toString());
System.out.println("The area is "+
rectangle.getArea());
System.out.println("The perimeter is " +
rectangle.getPerimeter() );
}
}
Creating a Multilevel Hierarchy
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// Add weight.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to
constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m)
{
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class Shipment extends BoxWeight {
double cost;
// construct clone of an object
Shipment(Shipment ob) { // pass object to constructor
super(ob);
cost = ob.cost;
}
// constructor when all parameters are specified
Shipment(double w, double h, double d,
double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}
// default constructor
Shipment() {
super();
cost = -1;
}
// constructor used when cube is created
Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}
class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =
new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " +
vol);
System.out.println("Weight of shipment1 is "
+ shipment1.weight);
System.out.println("Shipping cost: $" +
shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " +
vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" +
shipment2.cost);
}
}
• is the process by which one object acquires the properties of
another object.
Chapter ii(oop)
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members
of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Using the super Keyword
• A subclass inherits accessible data fields and methods from its
superclass.
• The keyword super refers to the superclass of the class in which
super appears. It can be used in two ways:
– To call a superclass constructor.
• super(), or super(parameters);
– To call a superclass method.
• super.method(parameters);
• public void printCircle() {
System.out.println("The circle is created " +
super.getDateCreated() + " and the radius is " + radius);}
• It is not necessary to put super before getDateCreated() in this case,
however, because getDateCreated is a method in the
GeometricObject class and is inherited by the Circle class.
Method Overriding
• Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
• hierarchy, when method in subclass has the same name and type
signature as a method in its superclass, then the method in the
subclass is said to override the method in the superclass.
• means a subclass method overriding a super class method.
• Benefit: avoid using method in class super
• To override a method, the method must be defined in the subclass
using the same signature and the same return type.
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b; }
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
} }
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c; }
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k); }
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
A subOba;
subOb.show(); // this calls show() in B } }
Overriding vs. Overloading
• Overloading means to define multiple methods with the same name
but different signatures.
• Overriding means to provide a new implementation for a method in
the subclass. The method is already defined in the superclass.
• To override a method, the method must be defined in the subclass
using the same signature and the same return type.
Using final to Prevent Overriding
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Using final to Prevent Inheritance
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Polymorphism (from a Greek word meaning “many forms”)
• three pillars of object-oriented programming are encapsulation,
inheritance, and polymorphism.
• A class defines a type. A type defined by a subclass is called a subtype
and a type defined by its superclass is called a supertype.
• SubClass is a subtype of SuperClass and SuperClass is a supertype for
SubClass.
• every circle is a geometric object, but not every geometric object is a
circle. Therefore, you can always pass an instance of a subclass to a
parameter of its superclass type
• In simple terms, polymorphism means that a variable of a supertype
can refer to a subtype object.
Method displayObject takes a parameter of the GeometricObject type. You
can invoke displayObject by passing any instance of GeometricObject (e.g., new Circle4(
1, "red", false) and new Rectangle1(1, 1, "black", false). An
object of a subclass can be used wherever its superclass object is used. This is commonly
known as polymorphism (from a Greek word meaning “many forms”). In simple terms,
polymorphism means that a variable of a supertype can refer to a subtype object.
Using Abstract Classes
• Any subclass of an abstract class must either implement all of the abstract methods
in the superclass, or be itself declared abstract.
– abstract type name(parameter-list);
• Not possible to instantiate an abstract class
• cannot be used to instantiate(represent) objects, used to create object references.
• classes become more specific and concrete with each new subclass
• Class design should ensure that a superclass contains common features of its
subclasses.
• Abstract method define them only in each subclass.
• abstract class cannot be instantiated using the new operator, but you can still
define its constructors, which are invoked in the constructors of its subclasses.
• A class that contains abstract methods must be abstract. However, it is possible to
define an abstract class that contains no abstract methods
Chapter ii(oop)
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
//A a=new A(); cannot be created object because of abstract class
B b = new B();
b.callme();
b.callmetoo();
}
}
A, it is not possible to instantiate an abstract class.
// Using abstract methods and classes.
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area();
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside
Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}
Packages
• a mechanism for partitioning the class name space
into more manageable chunks.
• unique name had to be used for each class to avoid
name collisions.
• Java uses file system directories to store packages
– package pkg1[.pkg2[.pkg3]];
– Ex: package java.awt.image; (be stored in javaawtimage
in a Windows environment)
D:MyPack => D:MyPackjavac AccountBalance.java=> D:java MyPack.AccountBalance.java
// A simple package
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n;
bal = b;
}
void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for(int i=0; i<3; i++) current[i].show();
}
}
D:worldHelloWorld
package world;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
D:worldjavac HelloWorld
D:java world.HelloWorld
Importing Packages
• import pkg1[.pkg2].(classname|*);
– import java.util.*;
class MyDate extends Date {
}
– class MyDate extends java.util.Date { }
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}
public void show() {
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}}
-------------------------------------------
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
Interface
• specify what a class must do, but not how it does it.
• similar to classes, but they lack instance variables, and their methods are declared without any body.
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
interface Callback {
void callback(int param);
}
class Client implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
class TestIface {
public static void main(String args[]) {
Callback c = new Client();
c.callback(42);
}
}
Note:
// Another implementation of Callback.
class AnotherClient implements Callback {
// Implement Callback's interface
public void callback(int p) {
System.out.println("Another version of
callback");
System.out.println("p squared is " + (p*p));
}
}
class TestIface2 {
public static void main(String args[]) {
Callback c = new Client();
AnotherClient ob = new AnotherClient();
c.callback(42);
c = ob; // c now refers to AnotherClient
object
c.callback(42);
}
}
callback called with 42
Another version of callback
p squared is 1764

More Related Content

PDF
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
PDF
Object Oriented Programming - 5. Class & Object
PPT
7_-_Inheritance
PPT
Best Guide for Javascript Objects
PDF
Lecture 4: Data Types
PPT
Defining classes-and-objects-1.0
KEY
Clojure Intro
PPTX
Chapter iii(oop)
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...
Object Oriented Programming - 5. Class & Object
7_-_Inheritance
Best Guide for Javascript Objects
Lecture 4: Data Types
Defining classes-and-objects-1.0
Clojure Intro
Chapter iii(oop)

What's hot (20)

PDF
Java OOP Programming language (Part 4) - Collection
PDF
From Java to Scala - advantages and possible risks
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
PDF
C# Starter L04-Collections
PDF
JavaScript, TypeScipt and React Native
DOCX
Python Metaclasses
PPTX
Dart London hackathon
PDF
Swift 3 Programming for iOS : Protocol
PPTX
11. session 11 functions and objects
PDF
4 gouping object
PPT
9 - OOP - Smalltalk Classes (b)
PDF
Hw09 Hadoop + Clojure
PPT
PPT
9 - OOP - Smalltalk Classes (a)
PDF
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
ODP
Getting started with Clojure
PDF
Backbone.js: Run your Application Inside The Browser
PPTX
Java Polymorphism Part 2
PDF
(3) cpp abstractions more_on_user_defined_types
PDF
The Ring programming language version 1.8 book - Part 7 of 202
Java OOP Programming language (Part 4) - Collection
From Java to Scala - advantages and possible risks
Java OOP Programming language (Part 8) - Java Database JDBC
C# Starter L04-Collections
JavaScript, TypeScipt and React Native
Python Metaclasses
Dart London hackathon
Swift 3 Programming for iOS : Protocol
11. session 11 functions and objects
4 gouping object
9 - OOP - Smalltalk Classes (b)
Hw09 Hadoop + Clojure
9 - OOP - Smalltalk Classes (a)
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Getting started with Clojure
Backbone.js: Run your Application Inside The Browser
Java Polymorphism Part 2
(3) cpp abstractions more_on_user_defined_types
The Ring programming language version 1.8 book - Part 7 of 202
Ad

Viewers also liked (12)

DOCX
Relación de ejemplos que se puede decir
PDF
Pam workshop qfd 151001 han lean qrm centrum
DOCX
Ayuda geogebra
PDF
JoseOVazquez12
PDF
Allan Wong-rotated
DOCX
Introduccion
PPTX
Campaña publicitaria
PDF
Cupcakes de nueces
PDF
Dipticos humanismo sevilla
PDF
Carmelas
DOCX
10.oraciones compuestas
PDF
BG Basics
Relación de ejemplos que se puede decir
Pam workshop qfd 151001 han lean qrm centrum
Ayuda geogebra
JoseOVazquez12
Allan Wong-rotated
Introduccion
Campaña publicitaria
Cupcakes de nueces
Dipticos humanismo sevilla
Carmelas
10.oraciones compuestas
BG Basics
Ad

Similar to Chapter ii(oop) (20)

PPTX
unit 2 java.pptx
PPTX
JAVA Module 2____________________--.pptx
PDF
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
PDF
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
PPTX
JAVA Module 2 ppt on classes and objects and along with examples
PDF
Java Basics - Part2
PPT
5.CLASSES.ppt(MB)2022.ppt .
PPTX
Class object method constructors in java
PPTX
Classes, Inheritance ,Packages & Interfaces.pptx
PPTX
UNIT_-II_2021R.pptx
PDF
Java Programming - 04 object oriented in java
PPT
Java tutorial for Beginners and Entry Level
PPTX
class object.pptx
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPT
Unit 1 Part - 3 constructor Overloading Static.ppt
PPTX
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
PPT
packages and interfaces
PPTX
Mpl 9 oop
PPTX
Java basics
unit 2 java.pptx
JAVA Module 2____________________--.pptx
Session 3 Constructors, Types, Overloading, Static MethodsNotes.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Classes, Objects and Method - Object Oriented Programming with Java
JAVA Module 2 ppt on classes and objects and along with examples
Java Basics - Part2
5.CLASSES.ppt(MB)2022.ppt .
Class object method constructors in java
Classes, Inheritance ,Packages & Interfaces.pptx
UNIT_-II_2021R.pptx
Java Programming - 04 object oriented in java
Java tutorial for Beginners and Entry Level
class object.pptx
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Unit 1 Part - 3 constructor Overloading Static.ppt
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
packages and interfaces
Mpl 9 oop
Java basics

More from Chhom Karath (20)

PDF
set1.pdf
PPTX
Set1.pptx
PDF
orthodontic patient education.pdf
PDF
New ton 3.pdf
PPTX
ច្បាប់ញូតុនទី៣.pptx
PPTX
Control tipping.pptx
PPTX
Bulbous loop.pptx
PPTX
brush teeth.pptx
PPTX
bracket size.pptx
PPTX
arch form KORI copy.pptx
PPTX
Bracket size
PPTX
Couple
PPTX
ច្បាប់ញូតុនទី៣
PPTX
PPTX
Shoe horn loop
PPTX
Opus loop
PPTX
V bend
PPTX
Closing loop
PPTX
Maxillary arch form
PPTX
Front face analysis
set1.pdf
Set1.pptx
orthodontic patient education.pdf
New ton 3.pdf
ច្បាប់ញូតុនទី៣.pptx
Control tipping.pptx
Bulbous loop.pptx
brush teeth.pptx
bracket size.pptx
arch form KORI copy.pptx
Bracket size
Couple
ច្បាប់ញូតុនទី៣
Shoe horn loop
Opus loop
V bend
Closing loop
Maxillary arch form
Front face analysis

Recently uploaded (20)

PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Cell Structure & Organelles in detailed.
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Supply Chain Operations Speaking Notes -ICLT Program
VCE English Exam - Section C Student Revision Booklet
Week 4 Term 3 Study Techniques revisited.pptx
O7-L3 Supply Chain Operations - ICLT Program
PPH.pptx obstetrics and gynecology in nursing
Anesthesia in Laparoscopic Surgery in India
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Cell Structure & Organelles in detailed.
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Basic Mud Logging Guide for educational purpose
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Microbial diseases, their pathogenesis and prophylaxis
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
2.FourierTransform-ShortQuestionswithAnswers.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf

Chapter ii(oop)

  • 2. Introducing Classes • A template for multiple objects with similar features. Classes embody all the features of a particular set of objects. • A class is a reference type, which means that a variable of the class type can reference an instance of the class. • An object represents an entity in the real world that can be distinctly identified. • object is an instance(Creating) of a class(Data member +Method member). • A class library is a set of classes. • Every Class is made up of two components: attributes and behavior. – Attributes:state of an object (also known as its properties or attributes) individual things differentiate one object from another and determine appearance, state, data field(Table): object’s data fields, or other qualities of that object. – Behavior: (also known as its actions) what instances of that class do when their internal state changes. • Methods are functions defined inside classes that operate on instances of those classes.
  • 4. • An object is an instance of a class. Default value= null • You can create many instances of a class. Creating an instance is referred to as instantiation. • Box mybox; // declare reference to object//a variable of the class type can reference an instance of the class • mybox = new Box(); // allocate a Box object//assigns its reference to Box • The dot operator links the name of the object with the name of an instance variable. • dot operator to access both the instance variables and the methods within an object. • references a data field in the object. • invokes a method on the object
  • 5. General form of class Public class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } }
  • 6. Circle: radius: double Circle(newRadius: double) getArea(): double TV: channel: int volumeLevel: int on: boolean +turnOn(): void +turnOff(): void +setChannel(newChannel: int): void +setVolume(newVolumeLevel: int): void +channelUp(): void +channelDown(): void +volumeUp(): void +volumeDown(): void
  • 7. public class Pet { public int age; float weight; float height; String color; public void sleep(){ System.out.println( "Good night, see you tomorrow"); } public void eat(){ System.out.println( "I’m so hungry…let me have a snack like nachos!"); } public String say(String aWord){ String petResponse = "OK!! OK!! " +aWord; return petResponse; } }
  • 8. public class Test { String make; String color; boolean engineState; void startEngine() { if (engineState == true) System.out.println("The engine is already on."); else { engineState = true; System.out.println("The engine is now on."); } } void showAtts() { System.out.println("This motorcycle is a " + color + " " + make); if (engineState == true) System.out.println("The engine is on."); else System.out.println("The engine is off."); }
  • 9. public static void main(String[] args) { Test m = new Test(); m.make = "Yamaha RZ350"; m.color = "yellow"; System.out.println("Calling showAtts..."); m.showAtts(); System.out.println("--------"); System.out.println("Starting engine..."); m.startEngine(); System.out.println("--------"); System.out.println("Calling showAtts..."); m.showAtts(); System.out.println("--------"); System.out.println("Starting engine..."); m.startEngine(); } }
  • 10. class Box { double width; double height; double depth; } class TestOOP1 { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); Box box2=new Box(); } }
  • 12. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) { width = w; height = h; depth = d; }} class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol);}}
  • 13. • c1 = c2, c1 points to the same object • referenced by c2. The object previously referenced by c1 is no longer useful and therefore is now known as garbage. Garbage occupies memory space. • object is no longer needed, you can explicitly assign null to a reference variable for the object.
  • 14. Garbage collection • allocated by using the new operator • Deallocation is called garbage collection. objectName=null; – The finalize( ) Method protected void finalize( ) { // finalization code here }
  • 15. Constructors• methods of a special type, known as constructors • A constructor must have the same name as the class itself. • It can be tedious to initialize all of the variables in a class each time an instance is created by Method set. • Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects. • A constructor initializes an object immediately upon creation. • look a little strange because they have no return type, not even void. • Constructors are designed to perform initializing actions, such as initializing the data fields of objects. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } Box mybox1 = new Box(); Box mybox2 = new Box(); Or Box(double w, double h, double d) { width = w; height = h; depth = d; } Box mybox1 = new Box(2,3,1); Box mybox2 = new Box(2,4,1);
  • 16. Overloading Constructors class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; }} class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } }
  • 17. The this Keyword • be used inside any method to refer to the current object. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } // Use this to resolve name-space collisions. Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
  • 18. Overloading Methods • two or more methods within the same class that share the same name, as long as their parameter declarations are different.
  • 19. class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); }}
  • 20. Using Objects as Parameters • Like passing an array, passing an object is actually passing the reference of the object. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // return true if o is equal to the invoking object boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } }
  • 21. class Box { double width; double height; double depth; Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class OverloadCons2 { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume(); System.out.println("Volume of cube is " + vol); vol = myclone.volume(); System.out.println("Volume of clone is " + vol); }}
  • 22. Returning Objectsclass Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } } class RetOb { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: " + ob2.a);}}
  • 23. Array of object • declares and creates an array of ten Circle objects: – Circle[] circleArray = new Circle[10]; • To initialize the circleArray, you can use a for loop like this one: for (int i = 0; i < circleArray.length; i++) { circleArray[i] = new Circle(); } • An array of objects is actually an array of reference variables • invoking circleArray[1].getArea() involves two levels of referencing, as shown in Figure 8.18. circleArray references the entire array. circleArray[1] references a Circle object. • When an array of objects is created using the new operator, each element in the array is a reference variable with a default value of null.
  • 26. Static Variables, Constants, and Methods • Static variables store values for the variables in a common memory location. • Static methods can be called without creating an instance of the class.
  • 29. Introducing Access Control • public specifier, then that member can be accessed by any other code. This is not good for 2 reason – 1. arbitrary value – 2. class becomes difficult to maintain and vulnerable to bugs. • private, then that member can only be accessed by other members of its class. To prevent direct modifications of data fields, you should declare the data fields private,using the private modifier. This is known as data field encapsulation. • protected applies only when inheritance is involved. • Colloquially, a get method is referred to as a getter (or accessor), and a set method is referred to as a setter (or mutator).
  • 31. Inheritance – a Fish is Also a Pet • Object-oriented programming allows you to derive new classes from existing classes called inheritance. • best way to design these classes so to avoid redundancy and make the system easy to comprehend and easy to maintain? • every person inherits some features from his or her parents. • behavior and attributes that are shared by many pets. • pets are different - dogs bark, fish swim and do not make sounds, parakeets talk better than dogs. But all of them eat, sleep, have weight and height. • Fish is a subclass of the class Pet or Pet as a template for creating a class Fish.
  • 32. class GeometricObject1 { public String color = "white"; private boolean filled; private java.util.Date dateCreated; public GeometricObject1() { dateCreated = new java.util.Date();} public GeometricObject1(String Color, boolean filled) {dateCreated = new java.util.Date(); this.color = color; this.filled = filled;} public String getColor() { return color;} public void setColor(String color) { this.color = color;} public boolean isFilled() { return filled;} public void setFilled(boolean filled) { this.filled = filled;} public java.util.Date getDateCreated() { return dateCreated; } public String toString() { return "created on " + dateCreated + "ncolor: " + color + " and filled: " + filled;}} class Circle4 extends GeometricObject1 { private double radius; public Circle4() {} public Circle4(double radius) { this.radius = radius; color=“red”;} public Circle4(double radius, String color, boolean filled) { this.radius = radius; setColor(color); setFilled(filled); } public double getRadius() { return radius;} public void setRadius(double radius) { this.radius = radius; } public double getArea() { return radius * radius * Math.PI;} public double getDiameter() { return 2 * radius; } public double getPerimeter() { return 2 * radius * Math.PI; } public void printCircle() { System.out.println("The circle is created " + " and the radius is " + radius); } }
  • 33. class Rectangle1 extends GeometricObject1 { private double width; private double height; public Rectangle1() {} public Rectangle1(double width, double height) { this.width = width; this.height = height;} public Rectangle1(double width, double height, String color, boolean filled) { this.width = width; this.height = height; setColor(color); setFilled(filled);} public double getWidth() { return width;} public void setWidth(double width) { this.width = width; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getArea() { return width * height; } public double getPerimeter() { return 2 * (width + height); } } public class Test3 { public static void main(String[] args) { Circle4 circle = new Circle4(1); System.out.println("A circle "+ circle.toString()); System.out.println("The radius is "+ circle.getRadius() ); System.out.println("The area is "+ circle.getArea()); System.out.println("The diameter is "+ circle.getDiameter()); Rectangle1 rectangle = new Rectangle1(2, 4); System.out.println("nA rectangle "+ rectangle.toString()); System.out.println("The area is "+ rectangle.getArea()); System.out.println("The perimeter is " + rectangle.getPerimeter() ); } }
  • 34. Creating a Multilevel Hierarchy class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // Add weight. class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; } // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) { super(w, h, d); // call superclass constructor weight = m; } // default constructor BoxWeight() { super(); weight = -1; } // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } }
  • 35. class Shipment extends BoxWeight { double cost; // construct clone of an object Shipment(Shipment ob) { // pass object to constructor super(ob); cost = ob.cost; } // constructor when all parameters are specified Shipment(double w, double h, double d, double m, double c) { super(w, h, d, m); // call superclass constructor cost = c; } // default constructor Shipment() { super(); cost = -1; } // constructor used when cube is created Shipment(double len, double m, double c) { super(len, m); cost = c; } } class DemoShipment { public static void main(String args[]) { Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41); Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28); double vol; vol = shipment1.volume(); System.out.println("Volume of shipment1 is " + vol); System.out.println("Weight of shipment1 is " + shipment1.weight); System.out.println("Shipping cost: $" + shipment1.cost); System.out.println(); vol = shipment2.volume(); System.out.println("Volume of shipment2 is " + vol); System.out.println("Weight of shipment2 is " + shipment2.weight); System.out.println("Shipping cost: $" + shipment2.cost); } }
  • 36. • is the process by which one object acquires the properties of another object.
  • 38. class A { int i, j; void showij() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
  • 39. Using the super Keyword • A subclass inherits accessible data fields and methods from its superclass. • The keyword super refers to the superclass of the class in which super appears. It can be used in two ways: – To call a superclass constructor. • super(), or super(parameters); – To call a superclass method. • super.method(parameters); • public void printCircle() { System.out.println("The circle is created " + super.getDateCreated() + " and the radius is " + radius);} • It is not necessary to put super before getDateCreated() in this case, however, because getDateCreated is a method in the GeometricObject class and is inherited by the Circle class.
  • 40. Method Overriding • Sometimes it is necessary for the subclass to modify the implementation of a method defined in the superclass. • hierarchy, when method in subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. • means a subclass method overriding a super class method. • Benefit: avoid using method in class super • To override a method, the method must be defined in the subclass using the same signature and the same return type.
  • 41. // Method overriding. class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // display k – this overrides show() in A void show() { System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); A subOba; subOb.show(); // this calls show() in B } }
  • 42. Overriding vs. Overloading • Overloading means to define multiple methods with the same name but different signatures. • Overriding means to provide a new implementation for a method in the subclass. The method is already defined in the superclass. • To override a method, the method must be defined in the subclass using the same signature and the same return type.
  • 43. Using final to Prevent Overriding class A { final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } }
  • 44. Using final to Prevent Inheritance final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... }
  • 45. Polymorphism (from a Greek word meaning “many forms”) • three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. • A class defines a type. A type defined by a subclass is called a subtype and a type defined by its superclass is called a supertype. • SubClass is a subtype of SuperClass and SuperClass is a supertype for SubClass. • every circle is a geometric object, but not every geometric object is a circle. Therefore, you can always pass an instance of a subclass to a parameter of its superclass type • In simple terms, polymorphism means that a variable of a supertype can refer to a subtype object.
  • 46. Method displayObject takes a parameter of the GeometricObject type. You can invoke displayObject by passing any instance of GeometricObject (e.g., new Circle4( 1, "red", false) and new Rectangle1(1, 1, "black", false). An object of a subclass can be used wherever its superclass object is used. This is commonly known as polymorphism (from a Greek word meaning “many forms”). In simple terms, polymorphism means that a variable of a supertype can refer to a subtype object.
  • 47. Using Abstract Classes • Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract. – abstract type name(parameter-list); • Not possible to instantiate an abstract class • cannot be used to instantiate(represent) objects, used to create object references. • classes become more specific and concrete with each new subclass • Class design should ensure that a superclass contains common features of its subclasses. • Abstract method define them only in each subclass. • abstract class cannot be instantiated using the new operator, but you can still define its constructors, which are invoked in the constructors of its subclasses. • A class that contains abstract methods must be abstract. However, it is possible to define an abstract class that contains no abstract methods
  • 49. // A Simple demonstration of abstract. abstract class A { abstract void callme(); // concrete methods are still allowed in abstract classes void callmetoo() { System.out.println("This is a concrete method."); } } class B extends A { void callme() { System.out.println("B's implementation of callme."); } } class AbstractDemo { public static void main(String args[]) { //A a=new A(); cannot be created object because of abstract class B b = new B(); b.callme(); b.callmetoo(); } } A, it is not possible to instantiate an abstract class.
  • 50. // Using abstract methods and classes. abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an abstract method abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } } class AbstractAreas { public static void main(String args[]) { // Figure f = new Figure(10, 10); // illegal now Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure figref; // this is OK, no object is created figref = r; System.out.println("Area is " + figref.area()); figref = t; System.out.println("Area is " + figref.area()); } }
  • 51. Packages • a mechanism for partitioning the class name space into more manageable chunks. • unique name had to be used for each class to avoid name collisions. • Java uses file system directories to store packages – package pkg1[.pkg2[.pkg3]]; – Ex: package java.awt.image; (be stored in javaawtimage in a Windows environment)
  • 52. D:MyPack => D:MyPackjavac AccountBalance.java=> D:java MyPack.AccountBalance.java // A simple package package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); } } class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++) current[i].show(); } }
  • 53. D:worldHelloWorld package world; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } D:worldjavac HelloWorld D:java world.HelloWorld
  • 54. Importing Packages • import pkg1[.pkg2].(classname|*); – import java.util.*; class MyDate extends Date { } – class MyDate extends java.util.Date { }
  • 55. package MyPack; public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } public void show() { if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); }} ------------------------------------------- import MyPack.*; class TestBalance { public static void main(String args[]) { /* Because Balance is public, you may use Balance class and call its constructor. */ Balance test = new Balance("J. J. Jaspers", 99.88); test.show(); // you may also call show() } }
  • 56. Interface • specify what a class must do, but not how it does it. • similar to classes, but they lack instance variables, and their methods are declared without any body. access interface name { return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; // ... return-type method-nameN(parameter-list); type final-varnameN = value; }
  • 57. interface Callback { void callback(int param); } class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } } class TestIface { public static void main(String args[]) { Callback c = new Client(); c.callback(42); } } Note: // Another implementation of Callback. class AnotherClient implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("Another version of callback"); System.out.println("p squared is " + (p*p)); } } class TestIface2 { public static void main(String args[]) { Callback c = new Client(); AnotherClient ob = new AnotherClient(); c.callback(42); c = ob; // c now refers to AnotherClient object c.callback(42); } } callback called with 42 Another version of callback p squared is 1764

Editor's Notes

  • #32: class Box { double width; double height; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } }