SlideShare una empresa de Scribd logo
1 de 42
© Amir Kirsh
Object Oriented Programming with Java
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
3
Classes and Objects
A class will look like this:
<Access-Modifier> class MyClass {
// field, constructor, and method declarations
}
To instantiate an object we will do:
MyClass instance = new MyClass(<constructor params>);
4
Accessibility Options
Example:
public class Person {
private String name;
protected java.util.Date birthDate;
String id; // default accessibility = package
public Person() {}
}
Four accessibility options:
– public – (default) = “package” **
– protected * – private
* protected is also accessible by package
** called also “package-private” or “package-friendly”
5
Static
Example:
public class Widget {
static private int counter;
static public getCounter() {return counter;}
}
int number = Widget.getCounter();
Static member can be accessed without an instance
(same as in C++)
Called sometimes “class variable”
as opposed to “instance variable”
6
The ‘this’ keyword
Example:
public class Point {
private int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
In Java ‘this’ is a reference to myself
(in C++ it is a pointer…)
The ‘this’ keyword is also used to call another constructor of
the same class – we will see that later
7
Defining constants
Example:
public class Thingy {
public final static doodad = 6; // constant
public final id; // constant variable
public Thingy(int id) {this.id = id;} // OK
// public set(int id) {this.id = id;} // error!
}
Though const is a reserved word in Java
it's actually not in use!
However the final keyword let's you define
constants and const variables
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
9
Constructors
Examples in following slides…
– Constructors in Java are very similar to C++
– You can overload constructors (like any other method)
– A constructor which doesn't get any parameter
is called “empty constructor”
– You may prefer not to have a constructor at all,
in which case it is said that you have by default
an “empty constructor”
– A constructor can call another constructor
of the same class using the ‘this’ keyword
– Calling another constructor can be done only
as the first instruction of the calling constructor
10
Constructors
Example 1:
public class Person {
String name = ""; // fields can be initialized!
Date birthDate = new Date();
public Person() {} // empty constructor
public Person(String name, Date birthDate) {
this(name); // must be first instruction
this.birthDate = birthDate;
}
public Person(String name) {
this.name = name;
}
}
11
Constructors
Example 2:
public class Person {
String name = "";
Date birthDate = new Date();
public Person(String name, Date birthDate) {
this.name = name;
this.birthDate = birthDate;
}
}
Person p; // OK
p = new Person(); // not good – compilation error
12
Initializer
Initializer is a block of instructions performed
right after the fields creation and before calling
the constructor
A class does not have to have an initializer and
indeed it usually doesn't
Example:
public class Thingy {
String s;
// the block underneath is an initializer
{ s="Hello"; }
}
Usually initializer would do
a more complex job…
13
Static Initializer
Static initializer is a block of instructions
performed the first time a class is loaded
Static initializer may be useful to perform
a one time initializations of static members
Example:
public class Thingy {
static String s;
// the block underneath is a static initializer
static { s="Hello"; }
}
Usually static initializer would
do a more complex job…
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
15
Inheritance
Some Terms
A class that is derived from another class is called a subclass
(also a derived class, extended class, or child class).
The class from which the subclass is derived is called a
superclass (also a base class or a parent class).
Excepting java.lang.Object, which has no superclass,
every class has exactly one and only one direct superclass
(single inheritance).
In the absence of any other explicit superclass, every class is
implicitly a subclass of Object.
A class is said to be descended from all the classes in its
inheritance chain stretching back to Object.
16
Inheritance
Examples in following slides…
– Class Object is the ancestor base class of all classes in Java
– There is no multiple inheritance in Java
– Inheritance is always “public” thus type is not stated
(no private or protected inheritance as in C++)
– Class can implement several interfaces (contracts)
– Class can be abstract
– Access to base class is done using the super keyword
– Constructor may send parameters to its base using the
‘super’ keyword as its first instruction
– If the base class does not have an empty constructor then
the class is required to pass parameters to its super
17
Inheritance
Example 1:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
// Override toString in class Object
public String toString() {
return name;
}
}
18
Inheritance
Example 1 (cont’):
public class Employee extends Person {
private Employee manager;
public Employee(String name, Employee manager) {
super(name); // must be first
this.manager = manager;
}
// Override toString in class Person
public String toString() {
return super.toString() +
(manager!=null? ", reporting to: " + manager :
" - I'm the big boss!");
}
}
19
Inheritance
Example 2:
abstract public class Shape {
// private Color line = Color.Black;
// private Color fill = Color.White;
public Shape() {}
/* public Shape(Color line, Color fill) {
this.line = line;
this.fill = fill;
} */
abstract public void draw();
abstract public boolean isPointInside(Point p);
}
20
Inheritance
Example 2 (cont’):
public class Circle extends Shape {
private Point center;
private double radius;
public Circle(Point center, double radius) {
this.center = center; this.radius = radius;
}
public void draw() {…} // use Graphics or Graphics2d
public boolean isPointInside(Point p) {
return (p.distance(center) < radius);
}
}
21
Inheritance
Example:
abstract public class Shape {
…
final public void setFillColor(Color color)
{<some implementation>}
}
The final keyword is used to forbid a method from being
override in derived classes
Above is relevant when implementing a generic algorithm in the
base class, and it allows the JVM to linkage the calls to the
method more efficiently
The final keyword can also be used on a class to prevent the
class from being subclassed at all
of course, final and abstract
don‘t go together (why?)
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
23
Interfaces
Examples in following slides…
– Interface is a contract
– An interface can contain method signatures
(methods without implementation) and static constants
– Interface cannot be instantiated, it can only be implemented
by classes and extended by other interfaces
– Interface that do not include any method signature is called
a marker interface
– Class can implement several interfaces (contracts)
– Class can announce on implementing an interface,
without really implementing all of the declared methods,
but then the class must be abstract
24
Interfaces
Example 1 – using interface Comparable:
// a generic max function
static public Object max(Comparable... comparables) {
int length = comparables.length;
if(length == 0) { return null; }
Comparable max = comparables[0];
for(int i=1; i<length; i++) {
if(max.compareTo(comparables[i]) < 0) {
max = comparables[i];
}
}
return max;
}
// calling the function can go like this:
String maxStr = (String) max("hello", "world", "!!!");
25
Interfaces
Example 2 – supporting foreach on our own type:
public interface Iterable<T> {
Iterator<T> iterator();
}
// example
public interface Collection<E> extends Iterable<E> {
…
Iterator<E> iterator();
…
} Exercise:
Write class NewString that will allow
iterating over its chars using "foreach"
To have your own class support iterating, using the "foreach“
syntax, the class should implement the interface Iterable:
26
Interfaces
Example 3 – supporting clone on our own type:
public interface Cloneable {}
Exercise:
Implement clone for class Person
To have your own class support the clone method
the class should implement the marker interface Cloneable:
27
Interfaces
Example 4 – new IHaveName interface:
public interface IHaveName {
String getName();
}
Exercise:
Create the IHaveName interface and
let class Person implement it
To allow name investigation we want to create a new IHaveName
interface:
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
29
Nested Classes
Examples in following slides…
Nested Classes are divided into two categories:
static and non-static.
Nested classes that are declared static are simply called
static nested classes
Non-static nested classes are called inner classes
Inner classes that are defined without having their own name
are called anonymous classes
30
Nested Classes
Example 1:
public class OuterClass {
private int a;
static public class InnerStaticClass {
public int b;
}
public class InnerClass {
public void setA(int a1) {
a = a1; // we have access to a !!!
}
}
}
31
Nested Classes
Example 1 (cont’):
OuterClass.InnerStaticClass obj1 =
new OuterClass.InnerStaticClass();
OuterClass.InnerClass obj2 =
new OuterClass().new InnerClass();
obj2.setA(3); // we modify a of OuterClass!!!
32
Nested Classes
Example 2 – anonymous class:
public interface IHaveName {
String getName();
}
void someFunction(IHaveName someoneWithName) {
System.out.println(someoneWithName.getName());
}
public static void main(String[] args) {
someFunction(new IHaveName() {
public String getName() { return "Momo"; }
});
}
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
34
Enums
Examples in following slides…
Structure for Constant Enumeration
Not an integer!
- May represent data (= have fields)
- May implement methods (member and static)
Automatically extends the Enum abstract type
Cannot extend other Classes or Enums,
but can implement interfaces
Cannot be extended (Enums are final)
35
Enums
Example 1:
public class Card {
public enum Rank {
DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE
}
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
private final Rank rank;
private final Suit suit;
private Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
…
36
Enums
Example 1 (cont’):
public class Card {
…
public String toString() { return rank + " of " + suit; }
private static final List<Card> _deck =
new ArrayList<Card>();
// Initialize the static deck
static {
for (Suit suit : Suit.values())
for (Rank rank : Rank.values())
_deck.add(new Card(rank, suit));
}
public static ArrayList<Card> newDeck() {
// Return copy of prototype deck
return new ArrayList<Card>(_deck);
}
}
37
Enums
Example 2:
public enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
// Do arithmetic op represented by this constant
double eval(double x, double y) {
switch(this) {
case PLUS: return x + y;
case MINUS: return x - y;
case TIMES: return x * y;
case DIVIDE: return x / y;
}
throw new AssertionError("Unknown op: " + this);
}
}
38
Enums
Example 3:
public enum Operation {
PLUS {
double eval(double x, double y) { return x + y; }
},
MINUS {
double eval(double x, double y) { return x - y; }
},
TIMES {
double eval(double x, double y) { return x * y; }
},
DIVIDE {
double eval(double x, double y) { return x / y; }
};
// Do arithmetic op represented by this constant
abstract double eval(double x, double y);
}
Agenda • All that is to know on class syntax
• Constructors and Initializers
• Inheritance and Polymorphism
• Interfaces
• Nested Classes
• Enums
• Exercise
40
Exercise 1
This exercise is called the Object Oriented Rectangles game.
Get from the command line the coordinates of two rectangles.
The “winning rectangle” is set according to these rules:
• If a rectangle is contained (even partially) in the other, the
contained (=inner) rectangle wins
• If no one contains the other, the bigger by both area and
perimeter wins
• If no one is bigger by both area and perimeter, we have a tie
Example
Rectangle A: 1 1 10 10 (which means: x1=1, y1=1, x2=10, y2=10)
Rectangle B: 5 5 10 10 (which means: x1=5, y1=5, x2=10, y2=10)
The winner is Rectangle B (contained in A!)
41
Exercise 2
Write the necessary classes to support the following main:
static public void main(String[] args) {
Expression e =
new Sum(
new Exponent(
new Number(2.0), new Number(3.0)),
new Sum(
new Number(1.0), new Number(-3.0)));
System.out.println(e + " = " + e.evaluate());
}
42

Más contenido relacionado

La actualidad más candente

Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
Chaffey College
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
jaimefrozr
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 

La actualidad más candente (20)

Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 
Applets in java
Applets in javaApplets in java
Applets in java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Python PPT
Python PPTPython PPT
Python PPT
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
C#.NET
C#.NETC#.NET
C#.NET
 

Similar a Java oops PPT

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
Svetlin Nakov
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
Narayana Swamy
 

Similar a Java oops PPT (20)

02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Core java oop
Core java oopCore java oop
Core java oop
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Inheritance
Inheritance Inheritance
Inheritance
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Inheritance
InheritanceInheritance
Inheritance
 
Java02
Java02Java02
Java02
 
Access Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and EncapsulationAccess Modifiers in C# ,Inheritance and Encapsulation
Access Modifiers in C# ,Inheritance and Encapsulation
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Introduction to object oriented programming concepts
Introduction to object oriented programming conceptsIntroduction to object oriented programming concepts
Introduction to object oriented programming concepts
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Z blue interfaces and packages (37129912)
Z blue   interfaces and  packages (37129912)Z blue   interfaces and  packages (37129912)
Z blue interfaces and packages (37129912)
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 

Java oops PPT

  • 1. © Amir Kirsh Object Oriented Programming with Java
  • 2. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 3. 3 Classes and Objects A class will look like this: <Access-Modifier> class MyClass { // field, constructor, and method declarations } To instantiate an object we will do: MyClass instance = new MyClass(<constructor params>);
  • 4. 4 Accessibility Options Example: public class Person { private String name; protected java.util.Date birthDate; String id; // default accessibility = package public Person() {} } Four accessibility options: – public – (default) = “package” ** – protected * – private * protected is also accessible by package ** called also “package-private” or “package-friendly”
  • 5. 5 Static Example: public class Widget { static private int counter; static public getCounter() {return counter;} } int number = Widget.getCounter(); Static member can be accessed without an instance (same as in C++) Called sometimes “class variable” as opposed to “instance variable”
  • 6. 6 The ‘this’ keyword Example: public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } In Java ‘this’ is a reference to myself (in C++ it is a pointer…) The ‘this’ keyword is also used to call another constructor of the same class – we will see that later
  • 7. 7 Defining constants Example: public class Thingy { public final static doodad = 6; // constant public final id; // constant variable public Thingy(int id) {this.id = id;} // OK // public set(int id) {this.id = id;} // error! } Though const is a reserved word in Java it's actually not in use! However the final keyword let's you define constants and const variables
  • 8. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 9. 9 Constructors Examples in following slides… – Constructors in Java are very similar to C++ – You can overload constructors (like any other method) – A constructor which doesn't get any parameter is called “empty constructor” – You may prefer not to have a constructor at all, in which case it is said that you have by default an “empty constructor” – A constructor can call another constructor of the same class using the ‘this’ keyword – Calling another constructor can be done only as the first instruction of the calling constructor
  • 10. 10 Constructors Example 1: public class Person { String name = ""; // fields can be initialized! Date birthDate = new Date(); public Person() {} // empty constructor public Person(String name, Date birthDate) { this(name); // must be first instruction this.birthDate = birthDate; } public Person(String name) { this.name = name; } }
  • 11. 11 Constructors Example 2: public class Person { String name = ""; Date birthDate = new Date(); public Person(String name, Date birthDate) { this.name = name; this.birthDate = birthDate; } } Person p; // OK p = new Person(); // not good – compilation error
  • 12. 12 Initializer Initializer is a block of instructions performed right after the fields creation and before calling the constructor A class does not have to have an initializer and indeed it usually doesn't Example: public class Thingy { String s; // the block underneath is an initializer { s="Hello"; } } Usually initializer would do a more complex job…
  • 13. 13 Static Initializer Static initializer is a block of instructions performed the first time a class is loaded Static initializer may be useful to perform a one time initializations of static members Example: public class Thingy { static String s; // the block underneath is a static initializer static { s="Hello"; } } Usually static initializer would do a more complex job…
  • 14. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 15. 15 Inheritance Some Terms A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class). Excepting java.lang.Object, which has no superclass, every class has exactly one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object. A class is said to be descended from all the classes in its inheritance chain stretching back to Object.
  • 16. 16 Inheritance Examples in following slides… – Class Object is the ancestor base class of all classes in Java – There is no multiple inheritance in Java – Inheritance is always “public” thus type is not stated (no private or protected inheritance as in C++) – Class can implement several interfaces (contracts) – Class can be abstract – Access to base class is done using the super keyword – Constructor may send parameters to its base using the ‘super’ keyword as its first instruction – If the base class does not have an empty constructor then the class is required to pass parameters to its super
  • 17. 17 Inheritance Example 1: public class Person { private String name; public Person(String name) { this.name = name; } // Override toString in class Object public String toString() { return name; } }
  • 18. 18 Inheritance Example 1 (cont’): public class Employee extends Person { private Employee manager; public Employee(String name, Employee manager) { super(name); // must be first this.manager = manager; } // Override toString in class Person public String toString() { return super.toString() + (manager!=null? ", reporting to: " + manager : " - I'm the big boss!"); } }
  • 19. 19 Inheritance Example 2: abstract public class Shape { // private Color line = Color.Black; // private Color fill = Color.White; public Shape() {} /* public Shape(Color line, Color fill) { this.line = line; this.fill = fill; } */ abstract public void draw(); abstract public boolean isPointInside(Point p); }
  • 20. 20 Inheritance Example 2 (cont’): public class Circle extends Shape { private Point center; private double radius; public Circle(Point center, double radius) { this.center = center; this.radius = radius; } public void draw() {…} // use Graphics or Graphics2d public boolean isPointInside(Point p) { return (p.distance(center) < radius); } }
  • 21. 21 Inheritance Example: abstract public class Shape { … final public void setFillColor(Color color) {<some implementation>} } The final keyword is used to forbid a method from being override in derived classes Above is relevant when implementing a generic algorithm in the base class, and it allows the JVM to linkage the calls to the method more efficiently The final keyword can also be used on a class to prevent the class from being subclassed at all of course, final and abstract don‘t go together (why?)
  • 22. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 23. 23 Interfaces Examples in following slides… – Interface is a contract – An interface can contain method signatures (methods without implementation) and static constants – Interface cannot be instantiated, it can only be implemented by classes and extended by other interfaces – Interface that do not include any method signature is called a marker interface – Class can implement several interfaces (contracts) – Class can announce on implementing an interface, without really implementing all of the declared methods, but then the class must be abstract
  • 24. 24 Interfaces Example 1 – using interface Comparable: // a generic max function static public Object max(Comparable... comparables) { int length = comparables.length; if(length == 0) { return null; } Comparable max = comparables[0]; for(int i=1; i<length; i++) { if(max.compareTo(comparables[i]) < 0) { max = comparables[i]; } } return max; } // calling the function can go like this: String maxStr = (String) max("hello", "world", "!!!");
  • 25. 25 Interfaces Example 2 – supporting foreach on our own type: public interface Iterable<T> { Iterator<T> iterator(); } // example public interface Collection<E> extends Iterable<E> { … Iterator<E> iterator(); … } Exercise: Write class NewString that will allow iterating over its chars using "foreach" To have your own class support iterating, using the "foreach“ syntax, the class should implement the interface Iterable:
  • 26. 26 Interfaces Example 3 – supporting clone on our own type: public interface Cloneable {} Exercise: Implement clone for class Person To have your own class support the clone method the class should implement the marker interface Cloneable:
  • 27. 27 Interfaces Example 4 – new IHaveName interface: public interface IHaveName { String getName(); } Exercise: Create the IHaveName interface and let class Person implement it To allow name investigation we want to create a new IHaveName interface:
  • 28. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 29. 29 Nested Classes Examples in following slides… Nested Classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes Non-static nested classes are called inner classes Inner classes that are defined without having their own name are called anonymous classes
  • 30. 30 Nested Classes Example 1: public class OuterClass { private int a; static public class InnerStaticClass { public int b; } public class InnerClass { public void setA(int a1) { a = a1; // we have access to a !!! } } }
  • 31. 31 Nested Classes Example 1 (cont’): OuterClass.InnerStaticClass obj1 = new OuterClass.InnerStaticClass(); OuterClass.InnerClass obj2 = new OuterClass().new InnerClass(); obj2.setA(3); // we modify a of OuterClass!!!
  • 32. 32 Nested Classes Example 2 – anonymous class: public interface IHaveName { String getName(); } void someFunction(IHaveName someoneWithName) { System.out.println(someoneWithName.getName()); } public static void main(String[] args) { someFunction(new IHaveName() { public String getName() { return "Momo"; } }); }
  • 33. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 34. 34 Enums Examples in following slides… Structure for Constant Enumeration Not an integer! - May represent data (= have fields) - May implement methods (member and static) Automatically extends the Enum abstract type Cannot extend other Classes or Enums, but can implement interfaces Cannot be extended (Enums are final)
  • 35. 35 Enums Example 1: public class Card { public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE } public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES } private final Rank rank; private final Suit suit; private Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } …
  • 36. 36 Enums Example 1 (cont’): public class Card { … public String toString() { return rank + " of " + suit; } private static final List<Card> _deck = new ArrayList<Card>(); // Initialize the static deck static { for (Suit suit : Suit.values()) for (Rank rank : Rank.values()) _deck.add(new Card(rank, suit)); } public static ArrayList<Card> newDeck() { // Return copy of prototype deck return new ArrayList<Card>(_deck); } }
  • 37. 37 Enums Example 2: public enum Operation { PLUS, MINUS, TIMES, DIVIDE; // Do arithmetic op represented by this constant double eval(double x, double y) { switch(this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } throw new AssertionError("Unknown op: " + this); } }
  • 38. 38 Enums Example 3: public enum Operation { PLUS { double eval(double x, double y) { return x + y; } }, MINUS { double eval(double x, double y) { return x - y; } }, TIMES { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; // Do arithmetic op represented by this constant abstract double eval(double x, double y); }
  • 39. Agenda • All that is to know on class syntax • Constructors and Initializers • Inheritance and Polymorphism • Interfaces • Nested Classes • Enums • Exercise
  • 40. 40 Exercise 1 This exercise is called the Object Oriented Rectangles game. Get from the command line the coordinates of two rectangles. The “winning rectangle” is set according to these rules: • If a rectangle is contained (even partially) in the other, the contained (=inner) rectangle wins • If no one contains the other, the bigger by both area and perimeter wins • If no one is bigger by both area and perimeter, we have a tie Example Rectangle A: 1 1 10 10 (which means: x1=1, y1=1, x2=10, y2=10) Rectangle B: 5 5 10 10 (which means: x1=5, y1=5, x2=10, y2=10) The winner is Rectangle B (contained in A!)
  • 41. 41 Exercise 2 Write the necessary classes to support the following main: static public void main(String[] args) { Expression e = new Sum( new Exponent( new Number(2.0), new Number(3.0)), new Sum( new Number(1.0), new Number(-3.0))); System.out.println(e + " = " + e.evaluate()); }
  • 42. 42