Java Specific Elements: Course Software Engineering in Electronics and Telecommunications English Classes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 61

Java Specific Elements

Course Software Engineering in


Electronics and Telecommunications
English classes

Overview
Interfaces in Java
Packages in Java
Inheritance in Java
Abstract classes and Interfaces in Java

Java Interfaces
As an abstract class defined by:

interface nume_interfata[extends nume_int1, , nume_intn] {


.. corp interfata
}
Members in an interface:

interface Interfata1{
//declarare de constanta statica
public static final int max = 200;
//declarare de metoda
public void metoda();
}

In Java 8 interfaces evolved to support default and static


methods.
A default method is an instance method defined in an interface
whose method header begins with the default keyword; it also
provides a code body. Every class that implements the interface
inherits the interface's default methods and can override them.
3

How to use a standard


interface
interface Int1{

public void metoda();

class C1 implements Int1{

public void metoda(){

System.out.println(mesaj din metoda

implementata);

class Test{

public static void main(String[] args){

Int1 obiect_interfata; //declararea unei referinte de tipul

interfetei
C1 obiect_clasa = new C1(); //instantierea clasei
obiect_interfata = obiect_clasa;//upcasting
//apelul metodei declarate in interfata si implementate in clasa
obiect_interfata.metoda();
}
}

Java 8 interfaces
public interface Addressable
{
String getStreet();
String getCity();

default String getFullAddress()


{

return getStreet()+", "+getCity();


}
}
6

interface X
{

static void foo()

System.out.println("foo");

}
}
class Y implements X
{
}
public class Z
{

public static void main(String[] args)

X.foo();

// Y.foo(); // won't compile

}
}
Expression Y.foo() will not compile because foo() is a static member of
interface X and not a static member of class Y.

Packages in Java
Definition: A collection of classes and
interfaces grouped with the same name as
an association. Are simple defined with:
package PackageName; //used with:
import PackageName.*;//or a CName for *

-It is possible in different packages, to


have classes with the same name
-Predefined packages of Java API
-User defined packages (implicit a default
package is created in Eclipse) access
mechanism
8

User packages access


a) set CLASSPATH= E:/;
The user package defined in a directory
with the same name as the package using
E as root without specifying the subdirectory in the classpath
b)current directory, we create a
subdirectory with the package name
c) compiling/interpreter options specified
by -classpath
9

Steps to Creating a
Program in Eclipse
To create a program in Eclipse:
1. Create a Project
2. Create a Package (inside the src folder
of the project)
3. Create a Class (inside the package)
4. Create and run Java code

10

Create a package in Eclipse


In the following steps you create a new package.
A good convention for the project and package name is to
use the same name for the top level package and the
project.
Implicit in Eclipse, Java will create a default package.
For example if you name your project:
com.example.javaproject
you should also use,
com.example.javaproject
as top level package name.
To create the:
de.vogella.eclipse.ide.first package,
select the src folder , right-click on it and select New

Package

11

12

One level package upDown

13

Create a Java class in the


package
Create a Java class. Right-click on your package and
select New Class.

Enter MyFirstClass as the class name and select


the public static void main (String[] args) flag.

14

Press the Finish button.


This creates a new file and opens the Java editor. Change
15
the class based on the following listing.


package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {


System.out.println("Hello Eclipse!");
}

}
You could also directly create new packages via this
dialog. If you enter a new package in this dialog, it is
created automatically.

16

One level package


package pack1;

class C1{//...

class C2{//...

interface I1{//...

}
import pack1.C1;
or
import pack1.*;
17

Multilevel packages
A hierarchy of packages
package pkg1[.pkg2[.pkg3]]
import pkg1[.pkg2].(className|*);
a)import java.util.*;
class MyDate extends Date{}
b) fully qualified name
class MyDate extends java.util.Date{}

18

Workbench Terminology
multi-level packages
Menu bar

Text
editor

Tool bar
Perspective
and
Fast View
bar

Outline
view

Resource
Navigator
view
Bookmarks
view

Properties
view
Message
area

19

Stacked
views

Tasks
view

Editor
Status
area

package Calin;
import java.io.*;
import java.util.*;
public class Citeste{
String citit;
public String CitesteTastatura(){
try
{
DataInputStream data=new DataInputStream(System.in);
citit=data.readLine();
}
catch(IOException ww)
{
System.out.print("A aparut o exceptie in pachetul propriu!!! ");
}
return citit;
}//end_met
}//class Citeste
20

// citeste un sir printr-o clasa cu un pachet propriu de la tastatura


import Calin.Citeste;
class aplicTast{
public static void main(String args[]){
String Sirtast;
System.out.println("Tastati un sir ");
Citeste ob=new Citeste();
Sirtast=ob.CitesteTastatura();
System.out.println("Ati tastat mai inainte "+Sirtast);
}
}//aplicTast
21

Refactoring
Refactoring is the process of restructuring the code
without changing its behavior. For example renaming a
Java class method or package is a refactoring activity.
For example to use the Rename refactoring, you can
right-click on your class (in the editor or Package
Explorer) and select Refactor Rename to rename
your class. Eclipse will make sure that all calls in your
Workspace to your class or method are renamed.
For a Project click on the arrow to expand your project,
for a package right click on the package, and select
Refactor then Rename, make sure that update
references is checked.

22

Inheritance in Java
Similar with C++ but with some
differences.
Object class is the first class upper in the
root
General form:
[lista_modificatori] class idClasa [extends

idClasaBaza] [implements lista_ interface]


{
corp_clasa
}
23

How Does Inheritance


Work in Java?
In Java, inheritance works with parent and child classes:

Parent classes define a set of fields/variables,


attributes, and a set of methods
Also known as a superclass, base class
Child classes are subsets of parent classes, and they
let us use the methods and fields from their parents
(that are not private), which is referred to as inheriting
methods.
Also known as a subclass, derived class
24

Superclass vs. Subclass


Classes can derive from, or evolve out of parent classes,
which means they contain the same methods and fields as
their parents, but can be considered a more specialized
form of their parent classes. The difference between a
subclass and a superclass is as follows:
Superclass

Subclass

The more general class from which The more specific class
that
other classes derive their methods derives or inherits from another
and data.
class (the superclass).

25

Superclasses contain methods and fields


that are passed down to all of their
subclasses.
Subclasses inherit methods and fields
of their superclasses.
A subclass may have define additional
methods or fields that the superclass does
not have.
26

Access modifiers:

public
private
protected subclass access in inheritance
process, but in Java is considered friendly
- private protected package private,
access in the same package by any class
(is not an explicit keyword!!!)
default no key word till Java8- able to
be accessed in the class and same
package by all classes.
27

Other Modifiers

final
For a variable: cannot be changed after instantiation
Widely used to make immutable classes
For a class: cannot be subclassed
For a method: cannot be overridden in subclasses
synchronized
Sets a lock on a section of code or method
Only one thread can access the code at any given time
volatile
Guarantees other threads see changes to variable
transient
Variables are not stored in serialized objects
native
Indicates that the method is implement using C or C++

(static and abstract are other modifiers that were presented)


28

Java @override annotation


Use it every time you override a method for two
benefits.
Do it so that you can take advantage of the
compiler checking to make sure you actually are
overriding a method when you think you are.
This way, if you make a common mistake of
misspelling a method name or not correctly
matching the parameters, you will be warned
that you method does not actually override as
you think it does.
Secondly, it makes your code easier to
understand because it is more obvious when
methods are overwritten.
29

public class Animal {

public void myMethod() {

System.out.println("The instance method in Animal.");

}
}//Base class
public class Cat extends Animal {

@Override

public void myMethod() {

System.out.println("The instance method in Cat.");

}
}//Derived class

Now if I make a mistake in typing the correct method


name then the compiler will give me an error only when I
use the @Override annotation The method myMethod() of type Cat must override
a superclass method
30

The toString() method


Idea
If you give a class a toString() method, that
method is automatically called whenever:
An object of that class is converted to a String
An object of that class is printed
Example
public class Person {
// Main code covered earlier
@Override
public String toString() {
return("PERSON: " + getFullName());
}
}//class
31

Enums in Java
Java enums are classes with named
instances
They do not correspond to ints as in C++
Quick example
public enum Month { JANUARY, , DECEMBER

}
doSomethingWith(Month.JANUARY);

Capabilities
Enums can have methods and constructors,
just like normal classes. Can be referenced in
switch statements.
32

Upcasting/downcasting
Casting:
Is the principle of changing the object
type during assignment.
Upcasting (from derived to base class):
loses access to specialized methods from
the sub-classed object instance.
Downcasting (from base to derived
class but with references): gains access to
specialized methods of the subclass.
33

Upcasting/downcasting
examples
class Bicicleta{
//
}//Base class
class BicicletaDeTeren extends Bicicleta{

//...

}//Derived class
Bicicleta b0 = new Bicicleta();
BicicletaDeTeren b1 = new BicicletaDeTeren();

34

Upcasting
b0 = b1; or
Bicicleta b2 = new BicicletaDeTeren();// or
Bicicleta b2 = (Bicicleta )new BicicletaDeTeren();

//cast not necessary

Realized implicit ( cast is not necessary) by


ignoring the supplementary derived attributes

35

Example from Oracle

36

Downcasting
A reference to a derived class may be
associated in explicit mode with cast
operator to a reference to the base class
that is associated to an object of derived
class.

37

Example from Oracle

38

package updown;
// Import

import java.lang.String;
// Clasa de baza
class Feline
{
boolean Foame = false;
void Vorbeste()
{
System.out.println("\n Raaa!!!- Base class");
}

void Cheama()
{
System.out.println("\nHai felina, felina...Base class");
if(Foame)
Vorbeste();
}
}//Feline
39

// Clasa derivata Pisica_de_Casa


class Pisica_de_Casa extends Feline
{
void Vorbeste()
{
System.out.println("\n Miau !!!- Derived Pisica_de_Casa");
}
}
// Clasa derivata Puma
class Puma extends Feline
{
void Vorbeste()
{
System.out.println("\nRoar!!!- Derived Puma");
}
}
40

class UpCasting // Clasa principala a aplicatiei


{
public static void main(String Args[])
{
Feline oFeline;
Pisica_de_Casa oPisicaCasa = new Pisica_de_Casa();
Puma oPuma = new Puma();
oPisicaCasa.Vorbeste();
oPisicaCasa.Cheama();
oPuma.Vorbeste();
oPuma.Cheama();
oFeline = oPisicaCasa; // Upcasting
oFeline.Vorbeste();
oFeline.Cheama();
oFeline = oPuma; // Upcasting
oFeline.Vorbeste();
oFeline.Cheama();
41

//downcasting
Pisica_de_Casa Pisica;
Pisica=new Pisica_de_Casa();
Feline rFeline;
rFeline=Pisica;
rFeline.Vorbeste();
Pisica_de_Casa rPisica;
rPisica=(Pisica_de_Casa)rFeline;
rPisica.Vorbeste();//down

} // end main
} // end UpCasting
42

Results up/downcasting
Miau !!!- Derived Pisica_de_Casa
Hai felina, felina...Base class
Roar!!!- Derived Puma
Hai felina, felina...Base class

Miau !!!- Derived Pisica_de_Casa


Hai felina, felina...Base class
Roar!!!- Derived Puma

Hai felina, felina...Base class


Miau !!!- Derived Pisica_de_Casa
Miau !!!- Derived Pisica_de_Casa

43

Downcasting is allowed when there is a


possibility that it succeeds at run time:
Object o = getSomeObject();//return a String
String s = (String) o; // this is allowed because
o could reference a String
In some cases this will not succeed:
Object o = new Object();
String s = (String) o; // this will fail at runtime,
because o doesn't reference a String as a

ClassCastException

Object o = "a String";


String s = (String) o; // this will work, since o
references a String

44

super and the inheritance


The super keyword is used to call a parent's
constructor.
It must be the first statement of the
constructor.
If it is not provided, a default call to
super() is inserted for you (will call the
empty constructor from the base class).
The super keyword may also be used to
invoke a parent's method or to access a
parent's (non-private) field.
45

super to access constructor


from the base class

//clasa de baza - CB

class Baza{

public Baza(){

System.out.println(Constr. fara parametri al CB);

public Baza(int x){

System.out.println(Constr. cu parametri al CB);

46

//clasa derivata

class Derivata{

public Derivata(){

super(7); //apelul constr. cu parametri din CB

System.out.println(Constructorul clasei derivate);

47

super to access methods from


the base class

//clasa de baza -CB


class Bicicleta{

public void metoda(){


System.out.println(Mesaj din CB");

}
}

48

//clasa derivata

class BicicletaDeTeren extends Bicicleta{

//redefinirea metodei din clasa de baza

public void metoda(){

super.metoda();
//apelul metodei originale din CB

System.out.println(Mesaj din clasa derivata");

49

class Test{

public static void main(String[] args){

Bicicleta b0 = new Bicicleta();

BicicletaDeTeren b1 = new BicicletaDeTeren();

b0.metoda();

b1.metoda();

}
50

super to access data from


base class

You can use super to access public or


protected data in the superclass.
If we wante to alter the Shape's color
variable throughout the code, we could
set the String variable color to be public
or protected.
public class Shape
{
protected String color;
}

51

public class Shape


{
public String color;
}
In the code, we could then change the
color without using an accessing method
like setColor().
super.color = Blue;
52

Interface inheritance
//prima interfata de baza

interface Int1{

public void m1();

//a 2-a interfata de baza

interface Int2{

public void m2();

//interfata derivata din primele doua

interface Int3 extends Int1, Int2{

public void m3();

53

//o clasa care foloseste interfata derivata

class MyClass implements Int3{

public void m1(){

System.out.println("metoda 1");

public void m2(){

System.out.println("metoda 2");

public void m3(){

System.out.println("metoda 3");

}
54

class Test{

public static void main(String[] args){

//instantierea clasei si apelarea metodelor

MyClass ob1 = new MyClass();

ob1.m1();

ob1.m2();

ob1.m3();

55

Abstract classes and


interfaces
Unlike interfaces, abstract classes can
contain fully implemented methods that they
pass on to any class that extends them.
public abstract class Bicycle {}
You can make a class abstract by using the
keyword abstract.
Abstract classes can also declare abstract
methods, which do not contain any
implementation.
56

Like interfaces, this means that the


subclasses must implement these methods
given by the prototype.
Abstract methods are declared with
the abstract keyword.
abstract public void setPrice();
It's important to remember that abstract
methods:
cannot have a method body
must be declared in an abstract class
must be overridden in a subclass
57

This forces programmers to implement and


redefine methods.
Typically, abstract classes contain abstract
methods, partially implemented methods, or
fully implemented methods.
If you have an abstract class with only
abstract methods, it is better to declare it as
an interface rather than an abstract class.
With abstract classes, subclasses can use
super to use their superclass's method.

58

Typically this is done by first overriding the


superclass's method, then calling the super,
or overridden method, and then adding code.
Unlike Interfaces, abstract classes may
have instance fields, concrete methods, and
constructors.
An interface (before JDK8) is similar to your
teacher saying Write a program that
calculates the user's weight on other planets
and include methods, getWeight(),

calcWeight(), getPlanetGravity(),
displayWeight().

59

An abstract class is similar to your


teacher saying Write code that calculates
the users weight on another planet,
include these methods, and I want you to
implement these methods in this way.
Additionally, some methods are already
provided for you.
now in Java8 interfaces are like abstract
classes
60

Java 8: Interfaces
and Abstract Classes

61

You might also like