Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
static vs final java, both are known access modifiers in Java doing different functionalities (used for different jobs). 1. static: static keyword can be applied to instance variables and methods but not to classes. When applied, variables and methods can be called without the help of an object. When a method or variable is called without object, encapsulation is not maintained. That is, with static variables and methods, encapsulation does not exist. 2. final: final keyword can be applied to all constructs – variables, methods and classes. When applied, final behaves very differently with each with different functionalities. Let us explore static vs final java programmatically. I) Usage of static Keyword Generally, an instance variable or method requires an object to call with. But static variables and methods do not require an object. Observe, the following code. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public class Employee { int age = 45; // non-static variable static double salary = 8877.66; // static variable public static void display() // static method { System.out.println("Hello World"); } public static void main(String args[]) { // System.out.println(age); // raises error, it is non-static and requires object System.out.println(salary); // works fine as salary is static, object not required display(); // works fine as display() is static, object not required } } In the above code, age is non-static and requires an object to call with. Observe, the main() method. salary being static does not require an object. Similarly with static display() method. It is called wihtout the need of an object. II) Usage of final Keyword As stated earlier, the final keyword can be applied in three places – variables, methods and classes. When applied it behaves differently. 1. A final variable cannot be reassigned. 2. A final method cannot be overridden. 3. A final class cannot be inherited. But one thing can be found in common among the above three, "final means something cannot be done". a) final with variables A final variable works like a constant of C/C++. That is, a final variable cannot be reassigned. Java does not support const keyword and its place uses final keyword. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public class Bank { public static void main(String args[]) { int rupees = 500; // non-final can be reassigned System.out.println("rupees before reassigned: " + rupees); rupees = 600; // non-final System.out.println("rupees after reassigned: " + rupees); final double $rate = 61.5; // final cannot be reassigned System.out.println("$ Rate is Rs." + $rate); // $rate = 62.8; // raises error } } The variable rupees is not final and thereby reassigned with a new value of 600. $rate is finaland thereby cannot be reassigned. b) final with methods If the super class does not permit the subclass to override, it simply declares the method as final. The final methods of super class cannot be overridden by subclass. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Manager { public final void doSomeThing() // observe final { System.out.println("Do it right now"); } } public class Worker extends Manager { public static void main(String args[]) { Worker w1 = new Worker(); w1.doSomeThing(); } } In the super class Manager, doSomeThing() is declared final. The subclass Worker is not permitted to override. Try once, it raises compilation error. If the super class have non-final methods (not shown in the code), the subclass can feel free to override at its convenience. c) final with classes The programmer may not like a class to be inherited by other classes because he would like to allow the accessibility throgh composition not by inheritance. 1 2 3 4 5 6 7 8 9 10 11 12 final class Fruit // observe, final class { String nature = "Seedless"; } public class Mango // extends Fruit raises compilation error { public static void main(String args[]) { Fruit f1 = new Fruit(); System.out.println("Fruit type is " + f1.nature); } } In the above code, Fruit is declared as final and thereby Mango cannot extend it. Then how it can make use of Fruit class methods? Simply by creating an object of Fruit and calling Fruitclass methods. This is known as composition. What is Composition in Java? Creating an object of other class in our class and calling other class variables and methods is known as composition (known as has-a relationship as one class "has a" object of other class). Here, object and method or variable belong to the same class. In contrast, in inheritance object belongs to subclass and variable or method belong to super class. Interfaces An interface is a contract: the guy writing the interface says, "hey, I accept things looking that way", and the guy using the interface says "Ok, the class I write looks that way". An interface is an empty shell, there are only the signatures of the methods, which implies that the methods do not have a body. The interface can't do anything. It's just a pattern. E.G (pseudo code): // I say all motor vehicles should look like this: interface MotorVehicle { void run(); int getFuel(); } // my team mate complies and writes vehicle looking that way class Car implements MotorVehicle { int fuel; void run() { print("Wrroooooooom"); } int getFuel() { return this.fuel; } } Implementing an interface consumes very little CPU, because it's not a class, just a bunch of names, and therefore there is no expensive look-up to do. It's great when it matters such as in embedded devices. Abstract classes Abstract classes, unlike interfaces, are classes. They are more expensive to use because there is a look-up to do when you inherit from them. Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying, "these classes should look like that, and they have that in common, so fill in the blanks!". e.g: // I say all motor vehicles should look like this : abstract class MotorVehicle { int fuel; // they ALL have fuel, so why not let others implement this? // let's make it for everybody int getFuel() { return this.fuel; } // that can be very different, force them to provide their // implementation abstract void run(); } // my team mate complies and writes vehicle looking that way class Car extends MotorVehicle { void run() { print("Wrroooooooom"); } } Implementation While abstract classes and interfaces are supposed to be different concepts, the implementations make that statement sometimes untrue. Sometimes, they are not even what you think they are. In Java, this rule is strongly enforced, while in PHP, interfaces are abstract classes with no method declared. In Python, abstract classes are more a programming trick you can get from the ABC module and is actually using metaclasses, and therefore classes. And interfaces are more related to duck typing in this language and it's a mix between conventions and special methods that call descriptors (the __method__ methods). As usual with programming, there is theory, practice, and practice in another language :-) shareimprove this answer edited Apr 29 '15 at 13:32 answered Dec 16 '09 at 8:37 nbro e-satis 3,04641030 224k80223279 149 practical explanation is always the best ! – Sarfraz Dec 16 '09 at 10:34 2 The key point about interfaces is not so much that they say what a clas make themselves useful to code that needs a Wizzler. Note that in ma thing that can Wizzle, nor the person who needs a Wizzler, will be the supercat Mar 27 '13 at 21:28 30 I don't think that CPU consumption is the highlight-worthy point on in 21:40 1 @AshwinP - see this question, specificially this answer. – Xynariz Oct 9 Now I understand that Declare method in interface is implicit Public, B otherwise it is Protected. Right @Xynariz – AshwinP Oct 10 '13 at 4:36 show 10 more comments up vote394do wn vote The key technical differences between an abstract class and an interface are: Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs. Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default). When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined. Similarly, an interface extending another interface is not responsible for implementing methodsfrom the parent interface. This is because interfaces cannot define any implementation. A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces. A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public). shareimprove this answer edited Feb 10 at 2:11 answered Dec 16 '09 at 10:11 Justin Johnson 20.3k74073 52 i think this is the best answer because it highlights all of the key differences. an example's not really necessary. – Joshua Kersey Jul 10 '11 at 18:01 1 And normally with classes you can instantiate an object from it unlike the abstract classes which CANNOTbe instantiated. – SASM Jul 9 '13 at 20:48 I thought a class that implement the interface need to define all the methods in the interface? – Jiazzy userDec 27 '13 at 12:33 @Jiazzyuser If an abstract class implements an interface, it does not have to actually define the interface's metho That requirement can be deferred to inheriting/child concrete classes. However, a concrete class must implemen all interface methods that are not implemented by its parent class. I'll add example to illustrate this point. – Justin Johnson Jan 28 '14 at 20:44 1 "When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined." - This is not true. Just as an interface can extend an interface without defining methods, an abstract class can inherit an abstract class without defining methods. – Nick Mar 10 '14 at 17:21 show 7 more comments up vote56dow n vote An explanation can be found here: http://www.developer.com/lang/php/article.php/3604111/PHP-5-OOP-InterfacesAbstract-Classes-and-the-Adapter-Pattern.htm An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class. An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface. Anyway I find this explanation of interfaces somewhat confusing. A more common definition is: An interface defines a contract that implementing classes must fulfill. An interface definition consists of signatures of public members, without any implementing code. shareimprove this answer edited Dec 16 '09 at 8:24 answered Dec 16 '09 at 8:18 Konamiman 26.9k1372104 3 This is the most correct answer, since PHP interfaces differ from other languages in that PHP interfaces ARE abstrac classes under the hood, whereas other languages' interfaces are signatures that classes must match. They behave t same as long as there are no errors though. – Tor Valamo Dec 16 '09 at 8:55 1 True, for PHP it's the real best anwser. But it's harder to get from the text blob than from a simple snippet. – esatis Dec 16 '09 at 12:15 From the definitions you provided, they look the same except for one detail: and interface is 100% abstract, while a abstract class is partially abstract and can have some method implementations (perhaps all methods can have implementations?). – jww Aug 23 '14 at 4:02 add a comment up vote43do wn vote Interface contains only definition / signature of functionality, and if we have some common functionality as well as common signature then there is a need of abstract class so through abstract class we can provide behavior as well as functionality both in the same time, developer inheriting abstract class can use this functionality and need to fill only in the blank. Taken From :http://www.dotnetbull.com/2011/11/difference-between-abstract-class-and.html http://www.dotnetbull.com/2011/11/what-is-abstract-class-in-cnet.htmlhttp://www.dotnetbull.com/2011/11/what-is-interface-in-c-net.html shareimprove this answer answered Sep 15 '13 at 8:59 Vivek 1,76486 3 You need to say what language this applies to ("Abstract class does not support multiple inheritance" is far from being universally true) – Ben Voigt Mar 7 '14 at 4:16 Last comparison is confusing as per table! Methods in interface can't be static but variables are static final Implemented methods in abstract class can be static – PK' Mar 9 '14 at 4:29 Typo it not Cunstructor .. Its Constructor.. – Orion Jul 18 '14 at 10:57 Member of the interface must be static final . Last statement is wrong. – Nepster Aug 5 '14 at 8:21 add a comment up vote15do wn vote Some important differences: In the form of a table: As stated by Joe from javapapers: 1.Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior. 2.Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. 3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. 4.Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”. 5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. 6.A Java class can implement multiple interfaces but it can extend only one abstract class. 7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. 8.In comparison with java abstract classes, java interfaces are slow as it requires extra indirection. Abstract class 1) Abstract class can have abstract and non- Interface Interface can have only abstract met abstractmethods. 2) Abstract class doesn't support multiple inheritance. Interface supports multiple inherita 3) Abstract class can have final, non-final, static and Interface has only static and final va non-static variables. 4) Abstract class can have static methods, main method Interface can't have static methods and constructor. or constructor. 5) Abstract class can provide the implementation of Interface can't provide the impleme interface. abstract class. 6) The abstract keyword is used to declare abstract class. The interface keyword is used to de 7) Example: Example: public abstract class Shape{ public interface Drawable{ public abstract void draw(); void draw(); } } Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%). Example of abstract class and interface in Java Let's see a simple example where we are using interface and abstract class both. 1. 2. 3. 4. 5. //Creating interface that has 4 methods interface A{ void a();//bydefault, public and abstract void b(); void c(); 6. void d(); 7. } 8. 9. //Creating abstract class that provides the implementation of one method of A interface 10. abstract class B implements A{ 11. public void c(){System.out.println("I am C");} 12. } 13. 14. //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods 15. class M extends B{ 16. public void a(){System.out.println("I am a");} 17. public void b(){System.out.println("I am b");} 18. public void d(){System.out.println("I am d");} 19. } 20. 21. //Creating a test class that calls the methods of A interface 22. class Test5{ 23. public static void main(String args[]){ 24. A a=new M(); 25. a.a(); 26. a.b(); 27. a.c(); 28. a.d(); 29. }} n this tutorial we will discuss the difference between overloading and overriding in Java. If you are new to these terms then refer the following posts: 1. Method overloading in java 2. Method overriding in java Overloading vs Overriding in Java 1. Overloading happens at compile-time while Overriding happens at runtime: The binding of overloaded method call to its definition has happens at compile-time however binding of overridden method call to its definition happens at runtime. 2. Static methods can be overloaded which means a class can have more than one static method of same name. Static methods cannot be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class. 3. The most basic difference is that overloading is being done in the same class while for overriding base and child classes are required. Overriding is all about giving a specific implementation to the inherited method of parent class. 4. Static binding is being used for overloaded methods anddynamic binding is being used for overridden/overriding methods. 5. Performance: Overloading gives better performance compared to overriding. The reason is that the binding of overridden methods is being done at runtime. 6. private and final methods can be overloaded but they cannot be overridden. It means a class can have more than one private/final methods of same name but a child class cannot override the private/final methods of their base class. 7. Return type of method does not matter in case of method overloading, it can be same or different. However in case of method overriding the overriding method can have more specific return type (refer this). 8. Argument list should be different while doing method overloading. Argument list should be same in method Overriding. Overloading example //A class for adding upto 5 numbers class Sum { int add(int n1, int n2) { return n1+n2; } int add(int n1, int n2, int n3) { return n1+n2+n3; } int add(int n1, int n2, int n3, int n4) { return n1+n2+n3+n4; } int add(int n1, int n2, int n3, int n4, int n5) { return n1+n2+n3+n4+n5; } public static void main(String args[]) { Sum obj = new Sum(); System.out.println("Sum System.out.println("Sum System.out.println("Sum System.out.println("Sum of of of of two numbers: "+obj.add(20, 21)); three numbers: "+obj.add(20, 21, 22)); four numbers: "+obj.add(20, 21, 22, 23)); five numbers: "+obj.add(20, 21, 22, 23, 24)); } } Output: Sum Sum Sum Sum of of of of two numbers: 41 three numbers: 63 four numbers: 86 five numbers: 110 Here we have 4 versions of same method add. We are overloading the method add() here. Overriding example package beginnersbook.com; class CarClass { public int speedLimit() { return 100; } } class Ford extends CarClass { public int speedLimit() { return 150; } public static void main(String args[]) { CarClass obj = new Ford(); int num= obj.speedLimit(); System.out.println("Speed Limit is: "+num); } } Output: Speed Limit is: 150 Difference between method and constructor in Java What is difference between method and constructor in Java is very common questions on beginner level Java interviews with 2 to 3 year experience. Since constructor is kind of special and it has it's own properties which separates it from any normal Java method, this question make sense. Main difference between Constructor and Method is that, you need to call method explicitly but constructor is called implicitly by Java programming language during object instantiation. It doesn't mean you can not call Constructor; if you have overloaded constructor than you can call them using this keyword as this() constructor, you can even call super class constructor using super() keyword, in-fact that is done automatically by Java compiler if no explicitly constructor is called and that is known as constructor chaining in Java. Like many other beginner level questions e.g. Vector vs ArrayList, We will see difference between method and constructor in Java in point form to understand important properties of each of them clearly. Method vs Constructor in Java Both method and constructor wraps bunch of code but constructor is very different than normal method in Java. Before seeing difference between Constructor and Method, let's see some common things between them. 1) Both method and Constructor can be overloaded or overridden in Java. Though calling mechanism of Constructor is different than method. you can call an overloaded constructor as this(argument) or super(argument) based upon whether its declared on same class or super class but for calling overloaded method or overridden method, you simply use method name. 2) You can make your constructor public, protected, private similar to your method in Java. By the way If you are not familiar with access modifier in Java than see Difference between public, protected and private keyword in Java. Now let's see some important difference between method and constructor in Java : 1) First difference between method vs constructor in Java is that name of constructor must be same with name of the Class but there is no such requirement for method in Java. methods can have any arbitrary name in Java. 2) Second difference between method and constructor in Java is that constructor doesn't have any return type but method has return type and return something unless its void. 3) Third difference between constructor and method in Java is that Constructors are chained and they are called in a particular order, there is no such facility for methods. 4) Unlike method, constructor, yet declared in class doesn't considered as member of Class. Constructors are not inherited by child classes but methods are inherited by child classes until they are made private. on which case they are only visible in class on which they are declared. Similarly private constructor means you can not create object of that class from outside, this is one of the technique used to implement Singleton pattern in Java. 5) Another difference between method and constructor in Java is that special keyword this and super is used to call constructor explicitly. no such thing for method, they have there own name which can be used to call them. That's all on difference between method and constructor in Java. You can compare method vs Constructor on different points but main thing is that they are used for object initialization, while method is used to perform a small unit of task. Read more: Types of inheritance in Java: Single,Multiple,Multilevel & Hybrid BY: CHAITANYA | LAST UPDATED: DECEMBER 6, 2013 Below are Various types of inheritance in Java. We will see each one of them one by one with the help of examples and flow diagrams. 1) 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 class of 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 isparent 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 Single and 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 using interfaces you can have multiple as well as hybrid inheritance in Java. Read the full article here – hybrid inheritance in java with example