Вы находитесь на странице: 1из 12

What is constructor and destructors?

A constructor is a class member Iunction in C and C# that has the same name as the class
itselI.
The purpose oI the constructor is to initialize all member variables when an object oI this class is
created. Any resources acquired such as memory or open Iiles are typically released in the
class destructor.
In addition to all oI the member Iunctions you'll create Ior your objects, there are two special
kinds oI Iunctions that you should create Ior every object. They are
called constructors and destructors. Constructors are called every time you create an object, and
destructors are called every time you destroy an object
class Player
int health;
int strength;
int agility;
Player(); // constructor - no return type
void move();
void attackMonster();
void getTreasure();
};
Destructors
estructors are less complicated than constructors. You don't call them explicitly (they are called
automatically Ior you), and there's only one destructor Ior each object. The name oI the
destructor is the name oI the class, preceded by a tilde (~). Here's an example oI a destructor:
Player::~Player()
strength 0;
agility 0;
health 0;
}

Since a destructor is called aIter an object is used Ior the last time,
Types OI methods:
Access methods , ModiIy methods
An accessor 2ethod is used when another 2ethod needs the value contained in a private data
member oI the class. An exa25e oI this would bemyClass::getata(), because all it
does is return the value oI the data. This type oI Iunction is useIul Ior making a read-only
variable.

ModiIy methods would be a 2ethod that modiIies a private data member inside a class.
An exa25e oI this would be myClass::setata(), because it changes the value oI data. Now, you
may be wondering why you would use a public member Iunction to modiIy a private member.
Why not just make the data member public?

Well, the whole goal oI object-oriented programming is to make classes relatively independant
objects. In other words, iI you suddenly want data to equal the value1, the only things you
should have to change is within the class itselI. By changing the setter 2ethod, the whole
thing is changed. II you had manually set the values Irom other classes, you would suddenly Iind
yourselI Iacing a whole ton oI coding. Another good exa25e oI this is iI you need to change
data types ina class.

Finally... managerial Iunctions. I've never heard such a description oI them beIore, so I'm only
guessing. I suppose it's a Iunction that manages an object, such as constructors/destructors
(memory management), or something such as a Iunction that does more than simply modiIy a
value in an object.

Static Method
Static methods can't use any instance variables.
A static method can be accessed without creating an instance oI the class. II you try to use a non-
static method and variable deIined in this class then the compiler will say that non-static variable
or method cannot be reIerenced Irom a static context. Static method can call only other static
methods and static variables deIined in the class.
Static methods cannot access non-static class level members and do not have a
'this' pointer. Instance methods can access those members, but must be called
through an object instantiation, which causes another step and level of
indirection.
The concept oI static method will get more clear aIter this program. First oI all create a
classowToAccessStaticMethod. Now deIine two variables in it, one is instance variable and
other is class variable. Make one static method named staticMethod() and second named
as nonStaticMethod(). Now try to call both the method without constructing a object oI the
class. You will Iind that only static method can be called this way.
The code of the 5rogra2 is given beow:
5ubic cass HowToAccessStaticMethod
int i;
static int j;
5ubic static void staticMethod()
System.out.println("you can access a static method this way");
}
5ubic void nonStaticMethod()
i100;
j1000;
System.out.println("on't try to access a non static method");
}
5ubic static void main(String|| args)
//i100;

j1000;
//nonStaticMethod();
staticMethod();
}
}

Static Variable
This Java programming example will teach you how you can deIine the static class variable in a
class. When a number oI objects are created Irom the same class, each instance has its own copy
oI class variables. But this is not the case when it is declared as static static.
static method or a variable is not attached to a particular object, but rather to the class as a
whole. They are allocated when the class is loaded. Remember, each time you call the instance
the new value oI the variable is provided to you. For example in the class StaticVariable each
instance has diIIerent copy oI a class variable. It will be updated each time the instance has been
called. We can call class variable directly inside the main method.
To see the use oI a static variable Iirst oI all create a class StaticVariabe. eIine one static
variable in the class. Now make a constructor in which you will increment the value oI the
static variable. Now make a object oI StaticVariabe class and call the static variable oI the
class. In the same way now make a second object oI the class and again repeats the process. Each
time you call the static variable you will get a new value.
Code of this exa25e is given beow:
5ubic cass StaticVariable
static int noOIInstances;
StaticVariable()
noOIInstances;
}
5ubic static void main(String|| args)
StaticVariable sv1 new StaticVariable();
System.out.println("No. oI instances Ior sv1 : " sv1.noOIInstances);

StaticVariable sv2 new StaticVariable();
System.out.println("No. oI instances Ior sv1 : " sv1.noOIInstances);
System.out.println("No. oI instances Ior st2 : " sv2.noOIInstances);

StaticVariable sv3 new StaticVariable();
System.out.println("No. oI instances Ior sv1 : " sv1.noOIInstances);
System.out.println("No. oI instances Ior sv2 : " sv2.noOIInstances);
System.out.println("No. oI instances Ior sv3 : " sv3.noOIInstances);
}
}
Output oI the program is given below:
As we can see in this example each object has its own copy oI class variable.
CABSTRACT Cass : Cass which consists one 5ure virtua function. In abstract cass are
usefu in inheritance conce5t
Po2or5his2 : the wa of Exhibiting one for2 in different for2. Static and dna2ic
Static 5o2or5his2 is 2ethod overoading Dna2ic Over ridding

Over oading goes in sa2e cass and over ridding goes in different casses

Packages :
" Method Overloading ?
Ans
Method overloading means having two or more methods with the same
name but different signatures in the same scope. These two methods may
exist in the same class or anoter one in base class and another in derived
class.

class Person
{
private String firstName;
private String lastName;
Person()
{
this.firstName = "";
this.lastName = "";
}
Person(String FirstName)
{
this.firstName = FirstName;
this.lastName = "";
}
Person(String FirstName, String LastName)
{
this.firstName = FirstName;
this.lastName = LastName;
}
}
Calling Overloaded Methods.
Person(); // as a constructor and call method without parameter
Person(userFirstName); // as a constructor and call method with one parameter(like User's
first Name)
Person(userFirstName,userLastName); // as a constructor and call method with one
parameter(like User's first Name)
When to use Method Overloading?
Generally, you should consider overloading a method when you have
required same reason that take different signatures, but conceptually do the
same thing.
-----------------------------------------------------------------------------------------
" Method Overriding?
Ans
Method overriding means having a different implementation of the same method in
the inherited class. These two methods would have the same signature, but different
implementation. One of these would exist in thebase class and another in the derived
class. These cannot exist in the same class.

Overriding methods
Overriding method definitions
In a derived class, if you include a method definition that has the same name and exactly
the same number and types of parameters as a method already defined in the base class,
this new definition replaces the old definition of the method.
Explanation
A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass
to modify the methods defined in the superclass. This is referred to
as method overriding. The following example demonstrates methodoverriding.
Step 1
In this example we will define a base class called Circle
class Circle
{
//declaring the instance variable
protected double radius;
public Circle(double radius)
{
this.radius = radius;
}
// other method definitions here
public double getArea()
{
return Math.PI*radius*radius;
}//this method returns the area of the circle
}// end of class circle
When the getArea method is invoked from an instance of the Circle class,
the method returns the area of the circle.
Step 2
The next step is to define a subclass to override the getArea() method in the Circle class.
The derived class will be the Cylinder class. The getArea() method in the Circle class
computes the area of a circle, while the getAreamethod in the Cylinder class computes the
surface area of a cylinder.
The Cylinder class is defined below.
class Cylinder extends Circle
{
//declaring the instance variable
protected double length;
public Cylinder(double radius, double length)
{
super(radius);
this.length = length;
}
// other method definitions here

public double getArea()
{
// method overriden here
return 2*super.getArea()+2*Math.PI*radius*length;
}//this method returns the cylinder surface area
}// end of class Cylinder
When the overriden method (getArea) is invoked for an object of the Cylinder class, the
new definition of themethod is called and not the old definition from the superclass(Circle).

Example code
This is the code to instantiate the above two classes
Circle myCircle;
myCircle = new Circle(1.20);
Cylinder myCylinder;
myCylinder = new Cylinder(1.20,2.50);

Virtua Function :
C virtual Iunction is a member Iunction oI a class, whose Iunctionality can be over-ridden in its
derived classes. The whole Iunction body can be replaced with a new set oI implementation in the
derived class. The concept oI c virtual Iunctions is diIIerent Irom C Function overloading.

C Virtual Function - Properties:
C virtual Iunction is,
A member Iunction oI a class
eclared with ;rtual keyword
Usually has a diIIerent Iunctionality in the derived class
A Iunction call is resolved at run-time
What is Encapsulation?
Encapsulation is binding of attributes and behaviors. Hiding the actual implementation and exposing
the functionality of any object. Encapsulation is the first step towards OOPS, is the procedure of
covering up of data and functions into a single unit (called class). Its main aim is to protect the data
from out sidemworld
Hiding the complexity. It is a process of defining communication interface for the functionality and
hiding rest of the things.
What is an Abstract class?
An abstract class is a special kind of class that cannot be instantiated. It normally contains one or
more abstract methods or abstract properties. It provides body to a class.
What is Polymorphism? And its type?
Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object
(or
reference) to assume (be replaced by) or become many different forms of object.
Example function overloading, function overriding, virtual functions. Another example can
be a plus? +? sign, used for adding two integers or for using it to concatenate two strings

There are two types of polymorphism-
1)Run time poIymorphism -Address of the function determine at the runtime is
known as runtime poIymorphism
2) CompiIe time poIymorphism- Address of the function determine at the compiIe time is known as
runtime poIymorphism

!ubIic: The data members and methods having public as access outside the class.
2. !rotected: The data members and methods declared as protected will be accessible to the class
methods
and the derived class methods only.
3. !rivate: These data members and methods will be accessible not from objects created outside the
class.
What do you mean by pure virtual functions?
A pure virtual member function is a member function that the base class forces derived classes to
provide. Normally these member functions have no implementation. Pure virtual functions are equated
to zero. class Shape
{
public virtual void draw() = 0;
};
What are virtual functions? Describe a circumstance in which virtual functions would be appropriate
Virtual functions are functions with the same function prototype that are defined throughout a class
hierarchy. At least the base class occurrence of the function is preceded by the keyword virtual. Virtual
functions are used to enable generic processing of an entire class hierarchy of objects through a base
class pointer. For example, in a shape hierarchy, all shapes can be drawn. If all shapes are derived
from a base class Shape which contains a virtual draw function, then generic processing of the
hierarchy can be performed by calling every shapes draw generically through a base class Shape
pointer.

What |s encapsu|at|on?
Enca5suation :
In Object Oriented Programming, encapsulation is an attribute oI object design. It means that all oI
the object's data is contained and hidden in the object and access to it restricted to members oI that
class.


What |s namespace?
a2es5ac
e :
Namespac
es allow to
group
entities
like
classes,
objects
and
Iunctions
under a
name. This
way the
namespace myNamespace

int a, b;
}
global
scope can
be divided
in "sub-
scopes",
each one
with its
own name.
The Iormat
oI
namespace
s is:
namespace
identiIier
entities }
Where
identiIier
is any
valid
identiIier
and
entities is
the set oI
classes,
objects
and
Iunctions
that are
included
within the
namespace
. For
example: 1
2 3 4

%ypes of inheritance:
(a) SingIe-LeveI Inheritance
hen one class is derived only from one base class then such inheritance is called
single-level inheritance. The single-level inheritance is shown below.
Base class
Derived class
(b) MuItiIeveI Inheritance
hen the single-level inheritance is extended to more levels then it is called
multilevel inheritance. n this inheritance one class is derived from another
derived class and the level of derivation can be extended to any number of levels.
For example, class C is derived from another derived class B which itself is
derived from class A.
A Base class
B
Derived class
Derived class
(c) MuItipIe Inheritance
A
C
A
B
hen single class inherits the properties from more than one base class, it is
called the multiple inheritance. n other words we can say that multiple
inheritance means that one class can have more than one base class. t allows us to
combine features of several existing classes into a single class as shown below
(d) HierarchicaI Inheritance
hen many subclasses inherit properties from a single base class, it is called as
hierarchical inheritance. The base class contains the features that are common to
the subclass and a subclass can inherit all or some of the features from the base
class as shown below
A
(e) Hybrid Inheritance
t is a combination of multiple inheritances and the hybrid inheritance. n hybrid
nheritance a class inherits from a multiple base class which itself inherits from a
single base class. This form of inheritance is known as hybrid inheritance. t is
shown below
A B
C
A
B C
A
B
C
D

Вам также может понравиться