CSS.103 Lecture 8
CSS.103 Lecture 8
Spring 2024
1
JAVA v.s. C++
Programming Language Comparison
2
Common format specifiers
•%s – String
•%d – Integer
•%f – Floating point number
•%t – Date/Time
•%x – Hexadecimal
Examples:
public class Example{
public static void main(String args[]){
String name = “Fatma";
String message = String.format("Hello, %s!", name);
System.out.println(message);
// Output: Hello, Fatma! 3
public class Example{
public static void main(String args[]){
String name = " Fatma ";
int age = 18;
double luckyNum = 123.456;
String formattedString = String.format("Name:
%s, Age: %d, Lucky No: $%.2f", name, age,
luckyNum);
System.out.println(formattedString);
// Output: Name: Fatma, Age: 18, Lucky No:
$123.456
}
}
4
Signatures
• In any programming language, a signature is what
distinguishes one function or method from another
• In Java, two methods have to differ in their names
or in the number or types of their parameters
– foo(int i) and foo(int i, int j) are different
– foo(int i) and foo(int k) are the same
– foo(int i, double d) and foo(double d, int i) are
different
5
◼ Polymorphism means many (poly) shapes (morph)
◼ In Java, polymorphism refers to the fact that you can
have multiple methods with the same name in the same
class
◼ There are two kinds of polymorphism:
◼ Overloading
◼ Two or more methods with different signatures
◼ Overriding
◼ Replacing an inherited method with another having the same signature
6
Overloading
class Test {
public static void main(String args[]) {
myPrint(5);
myPrint(5.0);
}
static void myPrint(int i) {
System.out.println("int i = " + i);
}
static void myPrint(double d) {
System.out.println("double d = " + d);
}
}
int i = 5
double d = 5.0
7
Overriding
class Animal {
public static void main(String args[]) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.print();
dog.print();
}
void print() {
System.out.println("Superclass Animal");
}
}
public class Dog extends Animal {
void print() {
System.out.println("Subclass Dog");
}
}
Superclass Animal
Subclass Dog
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Java
Abstraction
Interface
23
Java Abstraction
Abstract Class
Abstract Methods
24
Abstract Class
• Abstract classes may or may not contain abstract methods
• You have to place the abstract keyword before the method name
in the method declaration.
26
27
28
29
Java
30
Is-A and Has-A Relationship
31
Is-A Relationship
Inheritance is uni-directional.
For example, House is a Building. But Building is not a House.
32
Has-A Relationship
33
34
35
36
37
Java
Interface
38
Interface
Interfaces are just a definition of behavior.
42
43
Interface
44
45
Interface
46
47
48
Interface
49
50
END
51