Vous êtes sur la page 1sur 64

Programming

Language-
JAVA

Sonal
Maskeen
Declaring a class
• package
• Class name
• Constructor
• Fields
• methods

2
Class and Objects

public class MyClass {


int x = 5;
}

class OtherClass {
public static void main(String[] args) {
MyClass myObj = new MyClass();
System.out.println(myObj.x);
}
}
Global and local variables

public class MyClass {


int x = 10; //global variable

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 25; // x is now 25 //local variable
System.out.println(myObj.x);
}
}
Final keyword

public class MyClass {
final int x = 10;

public static void main(String[] args) {


MyClass myObj = new MyClass();
myObj.x = 25; // will generate an error:
cannot assign a value to a finalvariable
System.out.println(myObj.x);
}
}
• The final keyword is useful when you
want a variable to always store the
same value, like PI (3.14159...).

• The final keyword is called a "modifier".


Methods
Static and Public Methods
Calling a method using
Object
• Example explained
• 1) We created a custom Car class with the class keyword.
• 2) We created the fullThrottle() and speed() methods in
the Car class.
• 3) The fullThrottle() method and the speed() method will print
out some text, when they are called.
• 4) The speed() method accepts an int parameter
called maxSpeed - we will use this in 8).
• 5) In order to use the Car class and its methods, we need to
create an object of the Car Class.
• 6) Then, go to the main() method, which you know by now is a
built-in Java method that runs your program (any code inside
main is executed).
• 7) By using the new keyword we created a Car object with the
name myCar.
• 8) Then, we call the fullThrottle() and speed() methods on
the myCar object, and run the program using the name of the
object (myCar), followed by a dot (.), followed by the name of
the method (fullThrottle(); and speed(200);). Notice that we
add an int parameter of 200 inside the speed()method.
• Remember that..
• The dot (.) is used to access the object's attributes and
methods.
• To call a method in Java, write the method name followed by a
set of parentheses (), followed by a semicolon (;).
• A class must have a matching filename (Car and Car.java).
Constructors
• A constructor in Java is a special
method that is used to initialize
objects.
• The constructor is called when an
object of a class is created.
• It can be used to set initial values for
object attributes.
• Note that the constructor name must match
the class name, and it cannot have
a return type (like void).
• Also note that the constructor is called when
the object is created.
• All classes have constructors by default: if
you do not create a class constructor
yourself, Java creates one for you. However,
then you are not able to set initial values for
object attributes.
Constructor Parameters

• Constructors can also take


parameters, which are used to initialize
attributes.
The example adds an int y parameter to the constructor. Inside the constructor we set x to y
(x=y). When we call the constructor, we pass a parameter to the constructor (5), which will
set the value of x to 5:
• You can have as many parameters as you want:
Access
Modifiers

• The public keyword


is an access
modifier, meaning
that it is used to set
the access level for
classes, attributes,
methods and
constructors.
Example of Access Modifier
public class Person {
private String name;

public String getName() {


return name;
}

public void setName(String newName) {


this.name = newName;
}
}

public class MyClass {


public static void main(String[] args) {
Person myObj = new Person();
myObj.name = "John";
System.out.println(myObj.name);
}
}
• Error:
public class MyClass {
public static void main(String[] args)
{
Person myObj = new Person();
myObj.setName("John");
System.out.println(myObj.getName());
}
}
Inheritance
• In Java, it is possible to inherit attributes and
methods from one class to another. We
group the "inheritance concept" into two
categories:
• subclass (child) - the class that inherits from
another class
• superclass (parent) - the class being
inherited from
• To inherit from a class, use
the extends keyword.
Inheritance
class Animal{
void eat(){System.out.println("eating...");}
}

class Dog extends Animal{


void bark(){System.out.println("barking...");}
}

class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Types of Inheritance
• Why And When To Use "Inheritance"?
• - It is useful for code reusability: reuse
attributes and methods of an existing
class when you create a new class.
Static Binding & Dynamic
Binding
Polymorphism
class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}

class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Run time Polymorphism
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
Polymorphism
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig’s sound");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog’s sound");
}
}

class MyMainClass { Also write the code as:


public static void main(String[] args) {
Animal myAnimal = new Animal(); class MyMainClass {
Animal myPig = new Pig(); public static void main(String[] args) {
Animal myDog = new Dog(); Animal myAnimal;
myAnimal = new Pig();
myAnimal.animalSound(); myAnimal.animalSound();
myPig.animalSound();
myDog.animalSound(); myAnimal = new Dog();
} myAnimal.animalSound();
} }
class A What will be the output of the program?
{
int i = 10;
}
class B extends A
{
int i = 20;
}

public class MainClass


{
public static void main(String[] args)
{
A a = new B();
System.out.println(a.i);
}
}
Interface
• An interface is an abstract "class" that is used to
group related methods with "empty" bodies

• To access the interface methods, the interface must


be "implemented" (kinda like inherited) by another
class with the implements keyword (instead
of extends).
• The body of the interface method is provided by the
"implement" class
Interface
interface FirstInterface {
public void myMethod();
}

interface SecondInterface {
public void myOtherMethod();
}

class DemoClass implements FirstInterface, SecondInterface {


public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}

class MyMainClass {
public static void main(String[] args) {
DemoClass myObj = new DemoClass();
myObj.myMethod();
myObj.myOtherMethod();
}
}
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}

class Dog implements Animal {


public void animalSound() {
System.out.println("The dog’s sound");
}
public void sleep() {
System.out.println(“Dog is sleeping");
}
}

class MyMainClass {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.animalSound();
myDog.sleep();
}
}
Notes on Interfaces:

• It cannot be used to create objects (in the example


above, it is not possible to create an "Animal" object
in the MyMainClass)
• Interface methods does not have a body - the body
is provided by the "implement" class
• On implementation of an interface, you must
override all of its methods
• Interface methods are by default abstract and public
• Interface attributes are by
default public, static and final
• An interface cannot contain a constructor (as it
cannot be used to create objects)
Why And When To Use Interfaces?

• To achieve security - hide certain details and only


show the important details of an object (interface).
• Java does not support "multiple inheritance" (a class
can only inherit from one superclass). However, it
can be achieved with interfaces, because the class
can implement multiple interfaces.
• Note: To implement multiple interfaces, separate
them with a comma.
Arrays
Arrays vs Variables
Initialising an array
What could go wrong?
num [ 0 ] always OK
num [ 9 ] OK (given the above declaration)
num [ 10 ] illegal (no such cell from this declaration)
num [ -1 ] always NO! (illegal)
num [ 3.5 ] always NO! (illegal)
1d Arrays
• Arrays in Java are dynamic; they are allocated with
the new operator.
• Creating a (1d) array is a two-step process:

int[] x; //declare x to be an array of ints


//x has the value of null right now

x = new int[100]; //allocate 100 ints worth


Array Operations
• Subscripts always start at 0 as in C
• Subscript checking is done
automatically
• Certain operations are defined on
arrays of objects, as for other classes
– e.g. myArray.length == 5

45
An array is an object
• Person mary = new Person ( );
• int myArray[ ] = new int[5];
• int myArray[ ] = {1, 4, 9, 16, 25};
• String languages [ ] = {"Prolog",
"Java"};
• Since arrays are objects they are allocated
dynamically
• Arrays, like all objects, are subject to garbage
collection when no more references remain
– so fewer memory leaks
– Java doesn’t have pointers!
46
Array length
• When dealing with arrays, it is advantageous to
know the number of elements contained within the
array, or the array's "length". This length can be
obtained by using the array name followed by
.length. If an array named numbers contains 10
values, the code numbers.length will be 10.

** You must remember that the length of an array


is the number of elements in the array, which is one
more than the largest subscript.

http://mathbits.com/MathBits/Java/arrays/Declare.htm
Arrays
• Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for
each value.
• To declare an array, define the variable type
with square brackets:
• String[] cars;
• String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
• System.out.println(cars.length); //to find array length
as 4

Note: Array indexes start with 0: [0] is the first


element. [1] is the second element, etc.
• Loop Through an Array

String[] cars ={"Volvo", "BMW", "Ford", "Mazda"};


for (int i = 0; i < cars.length; i++)
{
System.out.println(cars[i]);
}

• Multidimensional Arrays

int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
2D arrays
Declaring a 2D array in Java
int[ ][ ] arrNumbers = new int[6][5];

6 = number of rows (DOWN)


5 = number of columns (ACROSS)
Instantiating a 2D array
Example: Fill a 2D array with “X”

Nothing!
You only put
Output data in, not
printed it!
Common mistake: printing a 2D array

You can’t just print the array name,


You have to print every element in the
array separately!

Output
Correct way: printing a 2D array
2 D array
Common 2D array tasks
• How to search the minimum and the
maximum element in an array ?
Algorithmic development

[0] [1] [2] [3] [4]


Robert Boris Brad George David

Example 1
Given the following array NAMES
and the following algorithm, which is constructed to reverse the contents of array NAMES

N = 5 // the number of elements in the array


K = 0 // this is the first index in the array

loop while K < N – 1


TEMP = NAMES[K]
NAMES [K] = NAMES [N – K –1]
NAMES [N – K –1] = TEMP
K=K+ 1
end loop

1.trace the algorithm, showing contents of the array after each execution of the loop [2 marks]
2.state the number of times the loop is executed [1 mark]
3.outline why the algorithm does not reverse the contents of the array NAMES, and how
this could be corrected. [2 marks]
1)

2) 4 times

3) Loop executes too many times;


Terminating value for controlling variable was not correctly set;
Condition should be changed to k < n div 2;
• How to reverse an array list ?
Example 2
A geography teacher is searching an array,
CITYNAMES, containing 100 names of cities and wants
to print out the names of the cities beginning with D.
Construct pseudocode to indicate how this may be done:

// FirstLetter(“CITY”) will return the


first letter of the word “CITY”
// Elements are stored in an array called
CITYNAMES

loop for C from 0 to 99


if FirstLetter(CITYNAMES[C]) = “D”
then endif
output CITYNAMES[C]
end loop
Example 3
A geography teacher is searching CITIES, a collection of city
names, and wants to print out the names of the cities beginning
with D.
Construct pseudocode to indicate how this may be done:

// FirstLetter(“CITY”) will return the first


letter of the word “CITY”

loop while CITIES.HasNextItem()


NAME = CITIES.getNext()
if FirstLetter(NAME) = “D” end if
output NAME
end loop

Students are not expected to construct code for SL paper 1, HL


paper 1 and HL paper 3 beyond the level of pseudocode. For SL
paper 2 and HL paper 2, the use of code will depend on the option.

Vous aimerez peut-être aussi