Anda di halaman 1dari 33

A CLASS REPRESENTS A SET OF OBJECTS which share the same structure and behaviors.

Inheritance(IS-A relation):
When one class is inherited from another class, it acquires the properties of that class.
Class employee{ Int salary=40000; } Class programmer extends employee{ Int bonus=10000; } Public static void main(){ Programmer p=new programmer(); //as employee is inherited by programmer class so programmer class will //aquire all the properties of employee class System.out.println(programmer salary is: +p.salary); System.out.println(programmer salary is: +p.bonus); }

There may be two types of relationships in inheritance. 1) HAS-A Relation (Aggregation) This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs. e.g
class operation{ int square(int n){ return n*n; } } Class circle{ Operation op; // aggregation Double pi=3.14; Void area(int radius){

Op=new operation(); Int rsquare=op.square(radius); //code reusability. Return pi*rsquare; } Void main(){ Circle c=new circle(); Double result=c.area(5); } }

When use aggregation ? Inheritance should be used only if the relation is-a is maintained throughout the lifetime of the object invoked; otherwise aggregation is the best choice. If new class is more or less original class (you need override) use inheritance If new class need same as the original class (no need to override) use aggregation Types of Inheritance:

Does java supports multiple inheritance? Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:
public class extends Animal, Mammal{}

However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance. Why multiple inheritance is not supported in Java ? Suppose
Class A{ Void msg() } Class B{ Void msg() } Class C extends A,B{ Void main(){ C obj=new C(); Obj.msg() // Now which msg method would be invoked ? ? } }

Is there any other way that you can achieve inheritance in Java? We can achieve inheritance by using extends/implements keywords but another way is to create the object of class A into class B. By this way we can use all the functionalities of class A in B. Inheritance Advantages & Disadvantages: Advantages:
1) Reusability -- facility to use public methods of base class without rewriting the same Extensibility -- extending the base class logic as per business logic of the derived class 2) Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class 3) Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.

Disadvantages:-

1) One of the main disadvantages of inheritance in Java (the same in other objectoriented languages) is the increased time/effort it takes the program to jump through all the levels of overloaded classes. If a given class has ten levels of abstraction above it, then it will essentially take ten jumps to run through a function defined in each of those classes 2) Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other. 3) Also with time, during maintenance adding new features both base as well as derived classes are required to be changed. If a method signature is changed then we will be affected in both cases (inheritance & composition) 4) If a method is deleted in the "super class" or aggregate, then we will have to refactor in case of using that method.Here things can get a bit complicated in case of inheritance because our programs will still compile, but the methods of the subclass will no longer be overriding superclass methods. These methods will become independent methods in their own right.

Overriding:
If a class inherits a method from its super class, then there is a chance to override the method provided that it is not marked final. The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means a subclass can implement a parent class method based on its requirement.

Example:
Let us look at an example.
class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object

Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class } }

This would produce following result:


Animals can move Dogs can walk and run

In the above example you can see that the even though b is a type of Animal it runs the move method in the Dog class. The reason for this is : In compile time the check is made on the reference type. However in the runtime JVM figures out the object type and would run the method that belongs to that particular object. Therefore in the above example, the program will compile properly since Animal class has the method move. Then at the runtime it runs the method specific for that object. Consider the following example :
class Animal{ public void move(){ System.out.println("Animals can move"); } } class Dog extends Animal{ public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); } } public class TestDog{ public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class b.bark(); } }

This would produce following result:


TestDog.java:30: cannot find symbol symbol : method bark() location: class Animal b.bark(); ^

This program will throw a compile time error since b's reference type Animal doesn't have a method by the name of bark.

Rules for method overriding:


The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the super class. The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or protected. Instance methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Constructors cannot be overridden.

What is static method in java?


Answer:

A Static method in Java is one that belongs to a class rather than an object of a class. Normal methods of a class can be invoked only by using an object of the class but a Static method can be invoked Directly. Example: public class A { ..... public static int getAge(){

.... } } public class B { ..... int age = A.getAge(); } In class B when we wanted the age value we directly called the method using the instance of the class instead of instantiating an object of the class. Tip: A static method can access only static variables. The reason is obvious. Something that is common to a class cannot refer to things that are specific to an object...

static variable

It is a variable which belongs to the class and not to object(instance) Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables A single copy to be shared by all instances of the class A static variable can be accessed directly by the class name and doesnt need any object Syntax : <class-name>.<variable-name>

static method

It is a method which belongs to the class and not to the object(instance) A static method can access only static data. It can not access non-static data (instance variables) A static method can call only other static methods and can not call a non-static method from it. A static method can be accessed directly by the class name and doesnt need any object Syntax : <class-name>.<method-name> A static method cannot refer to this or super keywords in anyway

Side Note:

main method is static , since it must be be accessible for an application to run , before any instantiation takes place.

Polymorphism: An object may takes different forms. There are two types of polymorphism: 1) Static (Compile Time) Polymorphism Method Overloading is an example of static polymorphism Methods having same names but different parameters is called method overloading. e.g
class DemoOverload{ public int add(int x, int y){ //method 1 return x+y; } public int add(int x, int y, int z){ //method 2 return x+y+z; } public int add(double x, int y){ //method 3 return (int)x+y; } public int add(int x, double y){ //method 4 return x+(int)y; } } class Test{ public static void main(String[] args){ DemoOverload demo=new DemoOverload(); System.out.println(demo.add(2,3)); //method System.out.println(demo.add(2,3,4)); //method System.out.println(demo.add(2,3.4)); //method System.out.println(demo.add(2.5,3)); //method } }

1 2 4 3

called called called called

At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile time polymorphism or static binding. 2) Dynamic (Run Time) Polymorphism

Suppose a sub class overrides a particular method of the super class. Lets say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called.

Have a look at the following example.


class Vehicle{ public void move(){ System.out.println(Vehicles can move!!); } } class MotorBike extends Vehicle{ public void move(){ System.out.println(MotorBike can move and accelerate too!!); } } class Test{ public static void main(String[] args){ Vehicle vh=new MotorBike(); vh.move(); // prints MotorBike can move and accelerate too!! vh=new Vehicle(); vh.move(); // prints Vehicles can move!! } }

It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference. In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called. As the method to call is determined at runtime, this is called dynamic binding or late binding.

The final Modifier: final Variables:


A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However the data within the object can be changed. So the state of the object can be changed but not the reference. With variables, the final modifier often is used with static to make the constant a class variable.

Example:
public class Test{ final int value = 10; // The following are examples of declaring constants: public static final int BOXWIDTH = 6; static final String TITLE = "Manager"; public void changeValue(){ value = 12; //will give an error } }

final Methods:
A final method cannot be overridden by any subclasses. As mentioned previously the final modifier prevents a method from being modified in a subclass. The main intention of making a method final would be that the content of the method should not be changed by any outsider.

Example:
You declare methods using the final modifier in the class declaration, as in the following example:
public class Test{ public final void changeName(){ // body of method } }

final Classes:
The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.

Example:
public final class Test { // body of class }

The abstract Modifier: abstract Class:


An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for the class to be extended. A class cannot be both abstract and final. (since a final class cannot be extended). If a class contains abstract methods then the class should be declared abstract. Otherwise a compile error will be thrown. An abstract class may contain both abstract methods as well normal methods.

Example:
abstract class Caravan{ private double price; private String model; private String year; public abstract void goFast(); //an abstract method public abstract void changeColor(); }

abstract Methods:
An abstract method is a method declared without any implementation. The methods body(implementation) is provided by the subclass. Abstract methods can never be final or strict. Any class that extends an abstract class must implement all the abstract methods of the super class unless the subclass is also an abstract class. If a class contains one or more abstract methods then the class must be declared abstract. An abstract class does not need to contain abstract methods. The abstract method ends with a semicolon. Example: public abstract sample();

Example:
public abstract class SuperClass{ abstract void m(); //abstract method } class SubClass extends SuperClass{ // implements the abstract method void m(){ ......... } }

Abstraction:
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class. If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclassed. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.
/* File name : Employee.java */ public abstract class Employee { private String name;

private String address; private int number; public Employee(String name, String address, int number) { System.out.println("Constructing an Employee"); this.name = name; this.address = address; this.number = number; } public double computePay() { System.out.println("Inside Employee computePay"); return 0.0; } public void mailCheck() { System.out.println("Mailing a check to " + this.name + " " + this.address); } public String toString() { return name + " " + address + " " + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } }

Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor. Now if you would try as follows:
/* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { /* Following is not allowed and would raise error */ Employee e = new Employee("George W.", "Houston, TX", 43); System.out.println("\n Call mailCheck using

Employee reference--"); e.mailCheck(); } }

When you would compile above class then you would get following error:
Employee.java:46: Employee is abstract; cannot be instantiated Employee e = new Employee("George W.", "Houston, TX", 43); ^ 1 error

Extending Abstract Class:


We can extend Employee class in normal way as follows:
/* File name : Salary.java */ public class Salary extends Employee { private double salary; //Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public void mailCheck() { System.out.println("Within mailCheck of Salary class "); System.out.println("Mailing check to " + getName() + " with salary " + salary); } public double getSalary() { return salary; } public void setSalary(double newSalary) { if(newSalary >= 0.0) { salary = newSalary; } } public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } }

Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee.

/* File name : AbstractDemo.java */ public class AbstractDemo { public static void main(String [] args) { Salary s = new Salary("Mohd Mohtashim", "Ambehta, 3, 3600.00); Salary e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

UP",

System.out.println("Call mailCheck using Salary reference --"); s.mailCheck(); System.out.println("\n Call mailCheck using Employee reference--"); e.mailCheck(); } }

This would produce following result:


Constructing an Employee Constructing an Employee Call mailCheck using Salary reference -Within mailCheck of Salary class Mailing check to Mohd Mohtashim with salary 3600.0 Call mailCheck using Employee reference-Within mailCheck of Salary class Mailing check to John Adams with salary 2400.

Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract. The abstract keyword is also used to declare a method as abstract.An abstract methods consist of a method signature, but no method body. Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:
public abstract class Employee { private String name; private String address; private int number; public abstract double computePay(); //Remainder of class definition

Declaring a method as abstract has two results:


The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well. Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they must be abstract,and any of their children must override it. Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated. If Salary is extending Employee class then it is required to implement computePay() method as follows:
/* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public double computePay() { System.out.println("Computing salary pay for " + getName()); return salary/52; } //Remainder of class definition }

Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface. The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Example:
Let us look at an example that depicts encapsulation:
/* File name : EncapTest.java */ public class EncapTest{ private String name; private String idNum; private int age; public int getAge(){ return age; } public String getName(){ return name; } public String getIdNum(){ return idNum; } public void setAge( int newAge){ age = newAge; } public void setName(String newName){ name = newName; } public void setIdNum( String newId){ idNum = newId; } }

The public methods are the access points to this class's fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be access as below::
/* File name : RunEncap.java */ public class RunEncap{ public static void main(String args[]){ EncapTest encap = new EncapTest(); encap.setName("James"); encap.setAge(20); encap.setIdNum("12343ms"); System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge()); }

This would produce following result:


Name : James Age : 20

Benefits of Encapsulation:

The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code.

Interfaces:
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface is similar to a class in the following ways:

An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface matching the name of the file. The bytecode of an interface appears in a .class file. Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:


You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces.

Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:
Let us look at an example that depicts encapsulation:
/* File name : NameOfInterface.java */ import java.lang.*; //Any number of import statements public interface NameOfInterface { //Any number of final, static fields //Any number of abstract method declarations\ }

Interfaces have the following properties:


An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */ interface Animal { public void eat(); public void travel(); }

Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract. Aclass uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */ public class MammalInt implements Animal{ public void eat(){ System.out.println("Mammal eats"); }

public void travel(){ System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){ MammalInt m = new MammalInt(); m.eat(); m.travel(); } }

This would produce following result:


Mammal eats Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method. The signature of the interface method and the same return type or subtype should be maintained when overriding the methods. An implementation class itself can be abstract and if so interface methods need not be implemented.

When implementation interfaces there are several rules:


A class can implement more than one interface at a time. A class can extend only one class, but implement many interface. An interface can extend another interface, similarly to the way that a class can extend another class.

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java public interface Sports { public void setHomeTeam(String name);

public void setVisitingTeam(String name); } //Filename: Football.java public interface Football extends Sports { public void homeTeamScored(int points); public void visitingTeamScored(int points); public void endOfQuarter(int quarter); } //Filename: Hockey.java public interface Hockey extends Sports { public void homeGoalScored(); public void visitingGoalScored(); public void endOfPeriod(int period); public void overtimePeriod(int ot); }

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface. The extends keyword is used once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as:
package java.util; public interface EventListener {}

An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces:

Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario. Adds a data type to a class: This situation is where the term tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.

What is a virtual function?


0 inShare digg

What are virtual function/method and virtual class in java?


Posted by admin on September 9, 2012 in Articles, Java No comments

Virtual Function/Method in Java In Java there is no keyword names virtual. Definition of Virtual from wiki: In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature to provide the polymorphic behavior. Therefore according to definition, every non-static method in JAVA is by default virtual method except final and private methods. The methods which cannot be inherited for polymorphic behavior is not a virtual method. public class Vehicle{ public void fuel(){ System.out.println(Fuel Vehicle);

} } public class Car extends Vehicle{ public void fuel(){ System.out.println(fuel Car); } } Here we are overriding fuel() method is virtual function/method in java. Virtual Class Abstract class is nothing but the pure virtual method equivalent in Java because all methods in abstract class are non private, non static and not final.

What is a friend class?

Question
What is the difference between public, private, and protected keywords? Do I even need to use them?

Answer
We use these keywords to specify access levels for member variables, or for member functions (methods).

Public variables, are variables that are visible to all classes. Private variables, are variables that are visible only to the class to which they belong. Protected variables, are variables that are visible only to the class to which they belong, and any subclasses.

Deciding when to use private, protected, or public variables is sometimes tricky. You need to think whether or not an external object (or program), actually needs direct access to the information. If you do want other objects to access internal data, but wish to control it, you would make it either private or protected, but provide functions which can manipulate the data in a controlled way. Take the following example :

public class bank_balance { public String owner; public int balance; public bank_balance( String name, int dollars ) { owner = name; if (dollars >= 0) balance = dollars; else dollars =0; } }

We have declared our string and integer to be public. This means that any object in the system can change the balance (setting it to zero, or even giving us a negative balance). This could cause the program to fall over, even though we wrote code in our constructor to prevent negative balances. Instead, we should have provided a getBalance/setBalance method, and made our balance private or proteced. Other objects can still access the data, but they can't put invalid data in.
public class bank_balance { public String owner; private int balance; public bank_balance( String name, int dollars ) { owner = name; if (dollars >= 0) balance = dollars; else dollars =0; } public int getBalance() { return balance; } public void setBalance(int dollars) { if (dollars >= 0) balance = dollars; else dollars = 0; } }

What is a Friend class ?

A friend class in C++, can access the "private" and "protected" members of the class in which it is declared as a friend. On declaration of friend class all member function of the friend class become friends of the class in which the friend class was declared. Friend status is not inherited; every friendship has to be explicitly declared. Friend classes can help in improving Encapsulation if used wisely.

Declaration
Classes are declared as friends within the definition of the class who is giving access to others; this prevents a class from giving itself access to another's protected members, which enforces encapsulation. The friend class has the same level of access irrespective of whether the friend declaration appears in either the public, protected or private sections of the class definition. Friend status is granted by using the friend keyword:
friend class ClassName;

Example
#include <iostream> class B { // B declares A as a friend... friend class A; private: void privatePrint() { std::cout << "hello, world" << std::endl; } }; class A { public: A() { B b; // ... and A now has access to B's private members b.privatePrint(); } }; int main() { A a; return 0; }

Advantages of using friend class


It provides additional functionality which is kept outside the class. It provides functions with data which is not normally used by the class. It provides a means of reducing algorithmic complexity by giving direct access to private and protected members to an external specified scope while not making the members more broadly accessible than necessary.

Two classes accessing private data to each other


Sometimes private data members are needed to be accessed and used by two different classes. In that case, friend class (or friend function) can be used. Friend class can access all data members of both the classes, even private and protected data. For that purpose, each class should be declared as friend in the other class. They should not be member of any one of the classes.

Scope
The class name which is introduced in the friend class declaration its scope is not in class granting friendship and also is not the member of the class granting access. If the name of the friend class is declared before the friend class declaration then the compiler searches for the class with the same name as the friend class at the scope of friend declaration. If the name of the friend class is same as that of the enclosing class which is nested then the nested class is a friend of enclosing class.
Example
class X{ class Y{ friend class Z; } }

is equivalent to
class Z; class X{ class Y{ friend class Z; }; };

Features

Friendships are not corresponded If class A is a friend of class B, class B is not automatically a friend of class A.

Friendships are not transitive If class A is a friend of class B, and class B is a friend of class C, class A is not automatically a friend of class C. Friendships are not inherited A friend of class Base is not automatically a friend of class Derived and vice versa; equally if Base is a friend of another class, Derived is not automatically a friend and vice versa. Access due to friendship is inherited A friend of Derived can access the restricted members of Derived that were inherited from Base. Note though that a friend of Derived only has access to members inherited from Base to which Derived has access itself, e.g. if Derived inherits publicly from Base, Derived only has access to the protected (and public) members inherited from Base, not the private members, so neither does a friend.

Friend and encapsulation


It is said that friend classes violate encapsulation as it has an access to internals of the class in which it is declared. A friend allows a class a by hiding details that may be needed by anything but the friends of the class. It is also said that friend classes can also enhance encapsulation [1] as it allows library writers to write an interface which is not compromised in order to allow proper internal referencing. NOTES: Why Constructors cannot be final/static or abstract? Constructors aren't inherited so can't be overridden so whats the use to have final constructor?? Constructor is called automatically when an instance of the class is created, it has access to instance fields of the class. What will be the use of a static constructor?? Constructor can't be overridden so what will you do with an abstract constructor??

There are two fundamental mechanisms for building new classes from existing ones: inheritance and aggregation---

Inheritance: (IS-A)
Wiki definition: inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined. Other definition: One class can use features from another class to extend its functionality (an Is a relationship) i.e., a Car is a Automobile. Inheritance is the inclusion of behaviour (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. The is a relationship is expressed with inheritance and has a relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class. Two of the main techniques for code reuse are class inheritance and object composition. Inheritance is uni-directional. For example Car is a Vehicle. But Vehicle is not a Car. Inheritance uses extends key word. Composition: is used when Car has a Engine. It is incorrect to say Car is a Engine. Composition simply means using instance variables that refer to other objects. The class Car will have an instance variable, which refers to a Engine object.
public class Vehicle{ ... } public class Car extends Vehicle { ... }

There are two types of inheritances: 1. Implementation inheritance (aka class inheritance) 2. Interface inheritance (aka type inheritance)

Which one to use? Prefer interface inheritance to implementation inheritance because it promotes the design

concept of coding to an interface and reduces coupling. Interface inheritance can achieve code reuse with the help of object composition. If you look at Gang of Four (GoF) design patterns, you can see that it favours interface inheritance to implementation inheritance.

ASSOCIATION: (HAS-A)
1. Composition 2. Aggregation Composition:
Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part CANNOT exist without a whole. If a whole is deleted then all parts are deleted. Wiki definition: object composition (not to be confused with function compo sition) is a way to combine simple objects or data types into more complex ones. Other definition: Allowing a class to contain object instances in other classes so they can be used to perform actions related to the class (an has a relationship) i.e., a person has the ability to walk.

As we know, inheritance gives us an 'is-a' relationship. To make the understanding of composition easier, we can say that composition gives us a 'part-of' relationship. Composition is shown on a UML diagram as a filled diamond.

If we were going to model a car, it would make sense to say that an engine is part-of a car. Within composition, the lifetime of the part (Engine) is managed by the whole (Car), in other words, when Car is destroyed, Engine is destroyed along with it.

public class Engine { ... } public class Car { Engine e = new Engine(); ....... }

As you can see in the example code above, Car manages the lifetime of Engine.

Which one to use?

The guide is that inheritance should be only used when subclass is a superclass.

Dont use inheritance just to get code reuse. If there is no is a relationship then use composition for code reuse. Overuse of implementation inheritance (uses the extends key word) can break all the subclasses, if the superclass is modified. Do not use inheritance just to get polymorphism. If there is no is a relationship and all you want is polymorphism then use interface inheritance with composition, which gives you code reuse

Aggregation:
Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part CAN exist without a whole. Just like composition, aggregation occurs when an object is composed of multiple objects. However, with composition, the internal objects (such as Tyre , Seat and Engine ) are owned by the main object ( Car ). If you destroy the Car , you also likely want the Tyre , Seat and Engine instances destroyed because they are a composition which, together, form a single Car.

The Car instance certainly doesn't own the Driver and you probably shouldn't assume that the Driver is destroyed if the Car is destroyed. Further, the Driver exists independent of the Car . The Driver can leave this Car and sit in another one. This independence makes a great deal of difference so this combination of objects is referred to as an aggregation instead of composition. When designing your applications, it is important to note that difference

public class Car { private Driver driver; public Car(Driver driver) { this.driver = driver; } ... } // Constructor

Car would then be used as follows:


Driver driver = new Driver (); Car ford = new Car(driver); or Car ford = new Car(new Driver());

Coupling is a back draw of Inheritance ? Inheritance causes strong coupling between classes this means that subclass depends upon parent class.

For Example:

Public class vehicle{ Public void work(){ System.out.println("Work of Animal"); } } public class car extends vehicle{ public void work(){ System.out.println("Work of vehicle"); } } subclass car overrides the function work(). If we change the signature of work() in vehicle, error occurs and program will not be compiled. As following Public class vehicle{ Public int work(){ //void is replaced with int System.out.println("Work of Animal"); Return 1; } } public class car extends vehicle{ public void work(){ //program will not be compiled until we replace void with int. it is //coupling. System.out.println("Work of Animal");

} }

When to prefer Inheritance? When there is a IS-A relationship and you have to use all the functions available in super class. When to prefer Aggregation over Inheritance? When you want to use some of the functions (part) of a class and there is Whole part relationship. It means that when the class A (whole) is using instance of class B (part), now if class A is destroyed, object of class B will not be destroyed. In the following example: public class Author { private String Name; private String email; private char gender; //----------------------public Author(String name,String email,char gender){ this.Name=name; this.email=email; this.gender=gender; } } public class Book { private String name; private Author author; // Aggregation, because we want to use authors information . private double price; private int qtyInStrock; //-----------------------public Book(String name,Author auther,double price){ this.name=name; this.author=author; this.price=price; }

public Book(String name,Author author,double price,int qtyInStock){ this.name=name; this.author=author; this.price=price; this.qtyInStrock=qtyInStock; } }

//--------------------------Main Code------------------------public static void main(String[] args) { // Object of author is created at run time and not created in the class, so if object of //Book would be deleted the object of Author remains exist. Author anAuthor = new Author("Hamid","Java Practices",'M'); Book aBook = new Book("Java for dummy", anAuthor, 19.95, 1000); // Use an anonymous instance of Author Book anotherBook = new Book("more Java for dummy", new Author("Hamid","Java Practices",'M'), 29.95, 888);

Anda mungkin juga menyukai