Sei sulla pagina 1di 5

Static vs non-static

public class Test {


int x;
int y;
static int z;

static double calculeazaDistanta (){


return 0.0;
}
double calculeazaInaltimea () {
return 0.0;
}
}

public static void main (String [] args){

Test t1 = new Test ();

t1.z = 10;
t1.x = 11;

Test.z = 5;
Test.y = 9; // non static y cannot be referenced from a static context

System.out.println(t1.z);

Test t2 = new Test ();

t2.calculeazaDistanta();
Test.calculeazaDistanta ();

Test t3 = new Test ();

t3.calculeazaInaltimea();
Test.calculeazaInaltimea(); // non static method cannot be referenced from a static
context

A static method belongs to the class itself and a non-static (aka instance) method belongs to each
object that is generated from that class. If your method does something that doesn't depend on the
individual characteristics of its class, make it static (it will make the program's footprint smaller).
Otherwise, it should be non-static

A static method belongs to the class and a non-static method belongs to an object of a class. That is,
a non-static method can only be called on an object of a class that it belongs to. A static method can
however be called both on the class as well as an object of the class. A static method can access only
static members. A non-static method can access both static and non-static members because at the
time when the static method is called, the class might not be instantiated (if it is called on the class
itself). In the other case, a non-static method can only be called when the class has already been
instantiated. A static method is shared by all instances of the class.

Polymorphism

Java supports polymorphism, the property of an object to take on many different forms. To
put this more precisely, a Java object may be accessed using a reference with the same type
as the object, a reference that is a superclass of the object, or a reference that defi nes an
interface the object implements, either directly or through a superclass. Furthermore, a cast
is not required if the object is being reassigned to a super type or interface of the object.

Proprietatea unei instante de a lua forma uneia dintre prototipurile superioare celui cu care a fost
creat.

Animal a = new Pisica ();

Encapsulation

Procedeu de scriere a unei clase care presupune ascunderea datelor in interiorul clasei pt ca
toate interactiunile cu ele sa se faca indirect prin metode: getter si setter.

public class Punct {

private int x,y;

public Punct (int x, int y) {


this.x = x;
this.y = y;
}

public void setX(int x) {


this.x = x;
}
public int getX() {
return this.x;
}

public void setY(int y) {


this.y = y;
}

public int getY() {


return this.y;
}
}

public static void main(String [] args) {


Punct p1 = new Punct(0,0);

//p1.x = 30;
//p1.y = 50;

p1.setX(30);
p1.setY(50);

Constructors

As you learned in Chapter 1, a constructor is a special method that matches the name of
the class and has no return type. Here’s an example:

public class Bunny {


public Bunny() {
System.out.println("constructor");
}
}

The name of the constructor, Bunny, matches the name of the class, Bunny, and there is
no return type, not even void. That makes this a constructor. Can you tell why these two
are not valid constructors for the Bunny class?

public bunny() { } // DOES NOT COMPILE


public void Bunny() { }

The first one doesn't match the classname because Java is case sensitive. Since it doesn't
match, Java knows it can't be a constructor and is supposed to be a regular method.
However, it is missing the return type and doesn't compile. The second method is a perfectly
good method, but is not a constructor because it has a return type.
Constructors are used when creating a new object. This process is called instantiation
because it creates a new instance of the class. A constructor is called when we write new
followed by the name of the class we want to instantiate. For example:

new Bunny()

When Java sees the new keyword, it allocates memory for the new object. Java also looks
for a constructor and calls it.

A constructor is typically used to initialize instance variables. The this keyword tells
Java you want to reference an instance variable. Most of the time, this is optional. The
problem is that sometimes there are two variables with the same name. In a constructor,
one is a parameter and one is an instance variable. If you don’t say otherwise, Java gives
you the one with the most granular scope, which is the parameter. Using this.name tells
Java you want the instance variable.

Here’s a common way of writing a constructor:


1: public class Bunny {
2: private String color;
3: public Bunny(String color) {
4: this.color = color;
5: } }

On line 4, we assign the parameter color to the instance variable color. The right
side of the assignment refers to the parameter because we don’t specify anything
special. The left side of the assignment uses this to tell Java we want it to use the
instance variable.

Overloading

Posibilitatea de a define in aceeasi clasa mai multe metode care au acelasi nume dar care
difera prin parametric (prin numar, prin tip, prin ordine).

Overriding

What if there is a method defined in both the parent and child class? For example, you may
want to define a new version of an existing method in a child class that makes use of the
definition in the parent class. In this case, you can override a method a method by declaring
a new method with the signature and return type as the method in the parent class. As
you may recall from Chapter 4, the method signature includes the name and list of input
parameters.

Overriding a method is not without limitations, though. The compiler performs the following
checks when you override a nonprivate method:
1. The method in the child class must have the same signature as the method in the parent
class.
2. The method in the child class must be at least as accessible or more accessible than the
method in the parent class.
3. The method in the child class may not throw a checked exception that is new or
broader than the class of any exception thrown in the parent class method.
4. If the method returns a value, it must be the same or a subclass of the method in the
parent class, known as covariant return types.

Clase abstracte

In general, dupa cum a fost prezentat in acest curs, clasele sunt folosite pentru definirea obiectelor si
crearea instantelor care interactioneaza pentru a forma aplicatia. Exista totusi si clase care nu pot fi
instantiate. Aceste tipuri de clase se numesc clase abstracte si sunt folosite pentru a generaliza
atribute si comportamente. Cu alte cuvinte, o clasa abstracta este creata nu pentru a fi instantiata ci
numai pentru a fi mostenita. Prin modul in care este definita poate cumula atribute sau
comportamente comune mai multor tipuri de obiecte. Prin definirea lor intr-o clasa abstracta,
acestea sunt scrise doar o singura data, urmand ca obiectele care au nevoie de acestea la definire sa
le mosteneasca de la clasa abstracta.
Mai mult decat atat, clasele abstracte pot defini comportamente abstracte. Comportamentele
abstracte sunt acele tipuri e comportamente care nu sunt definite in intregime. Clasa defineste doar
antetele lor (modificatori, tip, identificator si parametri) fara a da insa un set de instructiuni. Orice
clasa neabstracta care mosteneste de la clasa abstracta aceste comportamente trebuie sa suprascrie
comportamentele abstracte. Deoarece o instanta este o entitate neabstracta si prin urmare nu are
voie sa aiba comportamente abstracte. Din acest motiv comportamentele abstracte trebuiesc
suprascrise de catre orice clasa care poate defini instante. O clasa care nu suprascrie comportamente
abstracte mostenite trebuie definita abstract.
Clasele si comportamentele abstracte sunt definite folosind cuvantul cheie abstract.

Interfete

O interfata este similara unei clase abstracte. Diferenta dintre o clasa abstracta si o interfata este ca
interfata nu contine decat comportamente abstracte sau constante. Metodele intr-o interfata sunt
considerate abstracte, dar pentru definirea lor nu mai este folosit cuvantul cheie abstract. Imaginea
de mai jos prezinta un exemplu de definire a unei interfete. O interfata este creata cu ajutorul
cuvantului cheie interface.
Interfata poate fi implementata de o clasa prin folosirea cuvantului cheie implements.
Implementarea este similara cu mostenirea, dar este specifica interfetelor. Implementarea este
multipla in Java, asta inseamna ca o clasa poate implementa oricate interfete.

Potrebbero piacerti anche