Você está na página 1de 12

Q1) Access Modifier

Java provides a number of access modifiers to set access levels for classes,
variables, methods and constructors. The four access levels are:

Visible to the package. the default. No modifiers are needed.

Visible to the class only (private).

Visible to the world (public).

Visible to the package and all subclasses (protected).

Default Access Modifier - No keyword:


Default access modifier means we do not explicitly declare an access
modifier for a class, field, method, etc.
A variable or method declared without any access control modifier is
available to any other class in the same package.
The fields in an interface are implicitly public static final and the methods in
an interface are by default public.

Example:
Variables and methods can be declared without any modifiers, as in the
following examples:
String version = "1.5.1";

boolean processOrder() {
return true;
}

Private Access Modifier - private:


Methods, Variables and Constructors that are declared private can only be
accessed within the declared class itself.

Example:
The following class uses private access control:
public class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

Public Access Modifier - public:


A class, method, constructor, interface etc declared public can be accessed
from any other class. Therefore fields, methods, blocks declared inside a
public class can be accessed from any class belonging to the Java Universe.
However if the public class we are trying to access is in a different package,
then the public class still need to be imported.
Because of class inheritance, all public methods and variables of a class are
inherited by its subclasses.

Example:
The following function uses public access control:
public static void main(String[] arguments) {
// ...
}

The main() method of an application has to be public. Otherwise, it could


not be called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - protected:


Variables, methods and constructors which are declared protected in a
superclass can be accessed only by the subclasses in other package or any
class within the package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.
Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.

Example:
The following parent class uses protected access control, to allow its child
class override openSpeaker() method:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}

class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}

Here, if we define openSpeaker() method as private, then it would not be


accessible from any other class other than AudioPlayer. If we define it as
public, then it would become accessible to all the outside world. But our
intension is to expose this method to its subclass only, thats why we
used protected modifier.

Abstract Methods and Classes


An abstract class is a class that is declared

abstractit may or may not include abstract methods. Abstract classes cannot be

instantiated, but they can be subclassed.


An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);


If a class includes abstract methods, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent
class. However, if it does not, then the subclass must also be declared abstract.

Static Methods can access class variables without using object of the class. It can access non-static
methods and non-static variables by using objects. Static methods can be accessed directly in static
and non-static methods.
Example 1: public static void main itself is a static method
class Example5{
static int i;
static String s;
public static void main(String args[]) //Its a Static Method
{
Example5 obj=new Example5();
//Non Static variables accessed using object obj
System.out.println("i:"+obj.i);
System.out.println("s:"+obj.s);
}
}

Output:
i:0
s:null

Static Variables

Static variables are also known as Class Variables.

Such variables get default values based on the data type.

Data stored in static variables is common for all the objects( or instances ) of that Class.

Memory allocation for such variables only happens once when the class is loaded in the
memory.

These variables can be accessed in any other class using class name.

Unlike non-static variables, such variables can be accessed directly in static and non-static
methods.

Example 1: Static variables can be accessed without reference in Static method


class Example7{
static int var1;
static String var2;
//Its a Static Method
public static void main(String args[])
{
System.out.println("Var1 is:"+Var1);
System.out.println("Var2 is:"+Var2);
}
}

Output:
Var1 is:0
Var2 is:null

static is an important keyword in Java. Static can be applied to inner classes, variables and
methods. static belongs to Class in Java and value of static variable will always be same for all
instance of that Class. static methods are also binded at compile time as opposed to non static
method which are binded at runtime.

Java static keyword can be used in five cases as shown in below image.

Q.2 Constructor
Constructor in Java is block of code which is executed at the time of Object creation. But other than getting called,
Constructor is entirely different than methods and has some specific properties like name of constructor must be
same as name of Class. Constructor also can not have any return type, constructors are automatically chained by
using this keyword and super. Since Constructor is used to create object, object initialization code is normally hosted
in Constructor. Similar to method you can also overload constructor in Java. In this Java tutorial we will some
important points about constructor in Java which is worth remembering for any Java programmer. Its also worth
remember that any static initializer block is executed before constructor because they are executed when class is
loaded into memory while constructors are executed when you create instance of any object e.g.
using new() keyword.

Q.3)Why Java doesnt support multiple inheritance?


C++ , Common lisp and few other languages supports multiple inheritance while java doesnt support
it. It is just to remove ambiguity, becausemultiple inheritance can cause ambiguity in few scenarios.
One of the most common scenario is Diamond problem.
What is diamond problem?
Consider the below diagram which shows multiple inheritance as Class D extends both Class B & C. Now
lets assume we have a method in class Aand class B & C overrides that method in their own
way. Wait!!

here the problem comes Because D is extending both B & C so if D wants to use

the same method which method would be called (the overridden method of B or the overridden
method of C). Ambiguity. Thats the main reason why Java doesnt support multiple inheritance.

How to achieve multiple inheritance in Java using


interfaces?
interface X
{
public void myMethod();
}
interface Y

{
public void myMethod();
}
class Demo implements X, Y
{
public void myMethod()
{
System.out.println(" Multiple inheritance example using interfaces");
}
}

Q.4)single Inheritance
Single inheritance is damn easy to understand. When a class extends another one
class only then we call it a single inheritance. The below flow diagram shows that
class B extends only one class which is A. Here A is a parent classof B and B would be
a child class of A.

Single Inheritance example program in Java


Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2) Multiple Inheritance
Multiple Inheritance refers to the concept of one class extending (Or inherits)
more than one base class. The inheritance we learnt earlier had the concept of one
base class or parent. The problem with multiple inheritance is that the derived
class will have to manage the dependency on two base classes.

Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple
inheritance often leads to problems in the hierarchy. This results in unwanted
complexity when further extending the class.

Note 2: Most of the new OO languages like Small Talk, Java, C# do not support
Multiple inheritance. Multiple Inheritance is supported in C++.

3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit
from a derived class, thereby making this derived class the base class for the new
class. As you can see in below flow diagram C is subclass or child class of B and B is a
child class of A. For more details and example refer Multilevel inheritance in Java.

Multilevel Inheritance example program in Java


Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}

}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base class) of
B,C & D. Read More at Hierarchical Inheritance in java with example program.

5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination
of Singleand Multiple inheritance. A typical flow diagram would look like below. A

hybrid inheritance can be achieved in the java in a same way as


multiple inheritance can be!! Using interfaces. yes you heard it right. By
usinginterfaces you can have multiple as well as hybrid inheritance in Java.
Read the full article here hybrid inheritance in java with example program.

Você também pode gostar