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.
• 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.
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.
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).
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.
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
// 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

What's hot

Java OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - CollectionJava OOP Programming language (Part 4) - Collection
Java OOP Programming language (Part 4) - Collection
OUM SAOKOSAL
 
From Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risksFrom Java to Scala - advantages and possible risks
From Java to Scala - advantages and possible risks
SeniorDevOnly
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-CollectionsMohammad Shaker
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React Native
Mitchell Tilbrook
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
Nikunj Parekh
 
Dart London hackathon
Dart  London hackathonDart  London hackathon
Dart London hackathon
chrisbuckett
 
Swift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : ProtocolSwift 3 Programming for iOS : Protocol
Swift 3 Programming for iOS : Protocol
Kwang Woo NAM
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhúc Đỗ
 
4 gouping object
4 gouping object4 gouping object
4 gouping object
Robbie AkaChopa
 
03class
03class03class
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
Functional Object-Oriented Imperative Scala / 関数型オブジェクト指向命令型 Scala by Sébasti...
scalaconfjp
 
Getting started with Clojure
Getting started with ClojureGetting started with Clojure
Getting started with Clojure
John Stevenson
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
Howard Lewis Ship
 
Java Polymorphism Part 2
Java Polymorphism Part 2Java Polymorphism Part 2
Java Polymorphism Part 2
AathikaJava
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig
 
The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202The Ring programming language version 1.8 book - Part 7 of 202
The Ring programming language version 1.8 book - Part 7 of 202
Mahmoud Samir Fayed
 

What's hot (20)

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

Viewers also liked

Relación de ejemplos que se puede decir
Relación de ejemplos que se puede decirRelación de ejemplos que se puede decir
Relación de ejemplos que se puede decirAngela Ibt
 
Pam workshop qfd 151001 han lean qrm centrum
Pam workshop qfd 151001 han lean qrm centrumPam workshop qfd 151001 han lean qrm centrum
Pam workshop qfd 151001 han lean qrm centrum
vwiegel
 
Ayuda geogebra
Ayuda geogebraAyuda geogebra
Ayuda geogebra
Celeste Bustos
 
Campaña publicitaria
Campaña publicitariaCampaña publicitaria
Campaña publicitaria
cm2013ines
 
Cupcakes de nueces
Cupcakes de nuecesCupcakes de nueces
Cupcakes de nueces
tartasypostres
 
Dipticos humanismo sevilla
Dipticos humanismo sevillaDipticos humanismo sevilla
Dipticos humanismo sevillafjgn1972
 
Carmelas
CarmelasCarmelas
Carmelas
tartasypostres
 
10.oraciones compuestas
10.oraciones compuestas10.oraciones compuestas
10.oraciones compuestasmagodemoniako
 
BG Basics
BG BasicsBG Basics
BG Basics
ISKCON Chowpatty
 

Viewers also liked (12)

Relación de ejemplos que se puede decir
Relación de ejemplos que se puede decirRelación de ejemplos que se puede decir
Relación de ejemplos que se puede decir
 
Pam workshop qfd 151001 han lean qrm centrum
Pam workshop qfd 151001 han lean qrm centrumPam workshop qfd 151001 han lean qrm centrum
Pam workshop qfd 151001 han lean qrm centrum
 
Ayuda geogebra
Ayuda geogebraAyuda geogebra
Ayuda geogebra
 
JoseOVazquez12
JoseOVazquez12JoseOVazquez12
JoseOVazquez12
 
Allan Wong-rotated
Allan Wong-rotatedAllan Wong-rotated
Allan Wong-rotated
 
Introduccion
IntroduccionIntroduccion
Introduccion
 
Campaña publicitaria
Campaña publicitariaCampaña publicitaria
Campaña publicitaria
 
Cupcakes de nueces
Cupcakes de nuecesCupcakes de nueces
Cupcakes de nueces
 
Dipticos humanismo sevilla
Dipticos humanismo sevillaDipticos humanismo sevilla
Dipticos humanismo sevilla
 
Carmelas
CarmelasCarmelas
Carmelas
 
10.oraciones compuestas
10.oraciones compuestas10.oraciones compuestas
10.oraciones compuestas
 
BG Basics
BG BasicsBG Basics
BG Basics
 

Similar to Chapter ii(oop)

5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .
happycocoman
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
Raja Sekhar
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
kakarthik685
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
AshokKumar587867
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oop
AHHAAH
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .
happycocoman
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
RDeepa9
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
VeerannaKotagi1
 
class object.pptx
class object.pptxclass object.pptx
class object.pptx
Killmekhilati
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
java classes
java classesjava classes
java classes
Vasu Devan
 
Constructor&method
Constructor&methodConstructor&method
Constructor&method
Jani Harsh
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
yugandhar vadlamudi
 
WEB222-lecture-4.pptx
WEB222-lecture-4.pptxWEB222-lecture-4.pptx
WEB222-lecture-4.pptx
RohitSharma318779
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
Kuntal Bhowmick
 

Similar to Chapter ii(oop) (20)

5.CLASSES.ppt(MB)2022.ppt .
5.CLASSES.ppt(MB)2022.ppt                       .5.CLASSES.ppt(MB)2022.ppt                       .
5.CLASSES.ppt(MB)2022.ppt .
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdfJava-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf
 
unit 2 java.pptx
unit 2 java.pptxunit 2 java.pptx
unit 2 java.pptx
 
Mpl 9 oop
Mpl 9 oopMpl 9 oop
Mpl 9 oop
 
6.INHERITANCE.ppt(MB).ppt .
6.INHERITANCE.ppt(MB).ppt                    .6.INHERITANCE.ppt(MB).ppt                    .
6.INHERITANCE.ppt(MB).ppt .
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
 
class object.pptx
class object.pptxclass object.pptx
class object.pptx
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptxClasses, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
 
gdfgdfg
gdfgdfggdfgdfg
gdfgdfg
 
java classes
java classesjava classes
java classes
 
gdfgdfg
gdfgdfggdfgdfg
gdfgdfg
 
Constructor&method
Constructor&methodConstructor&method
Constructor&method
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Class introduction in java
Class introduction in javaClass introduction in java
Class introduction in java
 
WEB222-lecture-4.pptx
WEB222-lecture-4.pptxWEB222-lecture-4.pptx
WEB222-lecture-4.pptx
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 

More from Chhom Karath

set1.pdf
set1.pdfset1.pdf
set1.pdf
Chhom Karath
 
Set1.pptx
Set1.pptxSet1.pptx
Set1.pptx
Chhom Karath
 
orthodontic patient education.pdf
orthodontic patient education.pdforthodontic patient education.pdf
orthodontic patient education.pdf
Chhom Karath
 
New ton 3.pdf
New ton 3.pdfNew ton 3.pdf
New ton 3.pdf
Chhom Karath
 
ច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptxច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptx
Chhom Karath
 
Control tipping.pptx
Control tipping.pptxControl tipping.pptx
Control tipping.pptx
Chhom Karath
 
Bulbous loop.pptx
Bulbous loop.pptxBulbous loop.pptx
Bulbous loop.pptx
Chhom Karath
 
brush teeth.pptx
brush teeth.pptxbrush teeth.pptx
brush teeth.pptx
Chhom Karath
 
bracket size.pptx
bracket size.pptxbracket size.pptx
bracket size.pptx
Chhom Karath
 
arch form KORI copy.pptx
arch form KORI copy.pptxarch form KORI copy.pptx
arch form KORI copy.pptx
Chhom Karath
 
Bracket size
Bracket sizeBracket size
Bracket size
Chhom Karath
 
Couple
CoupleCouple
Couple
Chhom Karath
 
ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣
Chhom Karath
 
Game1
Game1Game1
Shoe horn loop
Shoe horn loopShoe horn loop
Shoe horn loop
Chhom Karath
 
Opus loop
Opus loopOpus loop
Opus loop
Chhom Karath
 
V bend
V bendV bend
V bend
Chhom Karath
 
Closing loop
Closing loopClosing loop
Closing loop
Chhom Karath
 
Maxillary arch form
Maxillary arch formMaxillary arch form
Maxillary arch form
Chhom Karath
 
Front face analysis
Front face analysisFront face analysis
Front face analysis
Chhom Karath
 

More from Chhom Karath (20)

set1.pdf
set1.pdfset1.pdf
set1.pdf
 
Set1.pptx
Set1.pptxSet1.pptx
Set1.pptx
 
orthodontic patient education.pdf
orthodontic patient education.pdforthodontic patient education.pdf
orthodontic patient education.pdf
 
New ton 3.pdf
New ton 3.pdfNew ton 3.pdf
New ton 3.pdf
 
ច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptxច្បាប់ញូតុនទី៣.pptx
ច្បាប់ញូតុនទី៣.pptx
 
Control tipping.pptx
Control tipping.pptxControl tipping.pptx
Control tipping.pptx
 
Bulbous loop.pptx
Bulbous loop.pptxBulbous loop.pptx
Bulbous loop.pptx
 
brush teeth.pptx
brush teeth.pptxbrush teeth.pptx
brush teeth.pptx
 
bracket size.pptx
bracket size.pptxbracket size.pptx
bracket size.pptx
 
arch form KORI copy.pptx
arch form KORI copy.pptxarch form KORI copy.pptx
arch form KORI copy.pptx
 
Bracket size
Bracket sizeBracket size
Bracket size
 
Couple
CoupleCouple
Couple
 
ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣ច្បាប់ញូតុនទី៣
ច្បាប់ញូតុនទី៣
 
Game1
Game1Game1
Game1
 
Shoe horn loop
Shoe horn loopShoe horn loop
Shoe horn loop
 
Opus loop
Opus loopOpus loop
Opus loop
 
V bend
V bendV bend
V bend
 
Closing loop
Closing loopClosing loop
Closing loop
 
Maxillary arch form
Maxillary arch formMaxillary arch form
Maxillary arch form
 
Front face analysis
Front face analysisFront face analysis
Front face analysis
 

Recently uploaded

Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
DhatriParmar
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 

Recently uploaded (20)

Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
The Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptxThe Diamond Necklace by Guy De Maupassant.pptx
The Diamond Necklace by Guy De Maupassant.pptx
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 

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.
  • 3.
  • 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.
  • 24.
  • 25.
  • 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.
  • 27.
  • 28.
  • 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).
  • 30.
  • 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.
  • 37.
  • 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
  • 48.
  • 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

  1. 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); } }