This document discusses object-oriented programming concepts in Java including:
- Classes define templates for objects with similar attributes and behaviors.
- Objects are instances of classes that represent real-world entities. They have attributes like properties and behaviors like methods.
- Methods operate on instances of classes. Constructors initialize objects upon creation.
- Overloading allows multiple methods or constructors with the same name but different parameters.
- Objects can be passed as parameters and returned from methods. Arrays can hold multiple object references.
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...Donny Wals
Learn how to use Combine, SwiftUI and Swift 5.2's callAsFunction to build an experimental localization system and familiarize yourself with these new APIs in iOS 13.
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...Donny Wals
Learn how to use Combine, SwiftUI and Swift 5.2's callAsFunction to build an experimental localization system and familiarize yourself with these new APIs in iOS 13.
From Java to Scala - advantages and possible risksSeniorDevOnly
Oleksii Petinov during his presentation gave the audience the overview of his vision of Scala pros and contras. In his vision Scala smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.
There is admittedly some truth to the statement that “Scala is complex”, but the learning curve is well worth the investment.
In the publication I briefly describe what metaclasses are in Python. The writeup is a living item and will be extended with more detail shortly.
Please enjoy and comment.
In this session you will learn:
Poly- many
morphism –forms.
An entity existing in more than one form.
methods,
objects.
For more information, visit: https://www.mindsmapped.com/courses/software-development/java-developer-training-for-beginners/
(3) cpp abstractions more_on_user_defined_typesNico Ludwig
- Advanced Creation of Instances on the Heap and the Freestore
-- The Operators new/delete, new[]/delete[] and Placement
- Controlling the Lifetime of an Object
-- Destructors and Resource Acquisition is Initialization (RAII)
-- Copies of Objects and Avoiding Copying Objects
- Instance- vs. Class Members
From Java to Scala - advantages and possible risksSeniorDevOnly
Oleksii Petinov during his presentation gave the audience the overview of his vision of Scala pros and contras. In his vision Scala smoothly integrates features of object-oriented and functional languages, enabling Java and other programmers to be more productive.
There is admittedly some truth to the statement that “Scala is complex”, but the learning curve is well worth the investment.
In the publication I briefly describe what metaclasses are in Python. The writeup is a living item and will be extended with more detail shortly.
Please enjoy and comment.
In this session you will learn:
Poly- many
morphism –forms.
An entity existing in more than one form.
methods,
objects.
For more information, visit: https://www.mindsmapped.com/courses/software-development/java-developer-training-for-beginners/
(3) cpp abstractions more_on_user_defined_typesNico Ludwig
- Advanced Creation of Instances on the Heap and the Freestore
-- The Operators new/delete, new[]/delete[] and Placement
- Controlling the Lifetime of an Object
-- Destructors and Resource Acquisition is Initialization (RAII)
-- Copies of Objects and Avoiding Copying Objects
- Instance- vs. Class Members
Class object method constructors in javaRaja Sekhar
Presented By :
N.V.Raja Sekhar Reddy
www.technolamp.co.in
www.programming9.com
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
Class is template for an object and object is instance of a class.
When we create a class, we are creating a new data type. we can use this type to declare objects of that type.
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
java notes, object oriented programming using java, java tutorial, lecture notes, java programming notes, java example programs, java programs with explanation, java source code with output, java programs, java coding, java codes, java slides, java notes,inheritance in java, java inheritancenotes, java inheritancet notes,different types of inheritance in Java,inheritance with an example, inheritance hierarchy in Java
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
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
}
}
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();
}
}
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
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);
}
}