Isn't this inheritance? If not please explain - java

So if I instantiate a class in another class in Java, isn't that inheritance, because I am calling its method?
For example,
public void updateStock(int stockNew){
stockFinal = stockNew;
Stock stock = new Stock();
stock.update(stockFinal);
}
Isn't that inheritance, because I am able to call the method, update().

This is inheritance:
public class Base
{
public String Hello() {
return "hello";
}
public class SubClass extends Base
{
}
Then it's used like this:
SubClass sc = new SubClass();
sc.Hello(); // returns "hello"
or
Base b = new SubClass();
b.Hello(); // calls the same as above
Or this, calling the base from an overridden method:
public class SubClass extends Base
{
//#Override
public String Hello(){
return super.Hello() + " + override!!!";
}
}
The keyword super refers to the classes ancestor.

No this is not inheritance. You are just calling the class itself.

No, that's not inheritance. Inheritance is when a class extends another class. Inheritance is about establishing an is-a relationship, like a Car is a Vehicle. Or a List is a Collection.
In your example, you're just creating a new object or another type and calling a method on it. If you, of type Human, are using a car, of type Car, that doesn't make a Car a Human.

No, that isn't inheritance. Inheritance is when a class extends or implements another class. For more information go here

Here
You can find an explanation of what is OOP and its principles!

This is not inheritance.
You are just creating a object of a class.
You can use method and data member of other class but object of base class can't use method or data member of your class.

No, using a class is not the same as inheriting the characteristics of a class.
See the official Java Tutorial to learn more.

Related

What is exact difference between Inheritance and Abstract class?

I know the fundamentals of OOP concepts[Inheritance, Abstraction, Encapsulation, Polymorphism]
We use Inheritance in case of Parent-Child relationship[Child can have all functionalities which Parent have and can add more functionality to itself too]
And we use Abstract class(In java) for a partial set of default implementations of methods in a class, which also can be implemented by simple Inheritance.
Look below example which makes my point clear.
Inheritance:
Parent class
public class Parent {
// This method will remain same for all child classes.No need to override
public void abc() {
System.out.println("Parent here");
}
// This methods need to be overridden from child class
public int getROI() {
return 0;
}
}
Child class
public class Child extends Parent{
#Override
public int getROI(){
return 5;
}
public static void main(String[] args) {
Child child =new Child();
child.abc();
System.out.println(child.getROI());
}
}
Abstract Class:
Parent class
abstract class Parent {
// This method will remain same for all child classes.No need to override
public void abc() {
System.out.println("Parent here");
}
// This methods need to be implemented from child class
public abstract int getROI();
}
Child class
public class Child extends Parent{
public int getROI(){
return 5;
}
public static void main(String[] args) {
Child child =new Child();
child.abc();
System.out.println(child.getROI());
}
}
For above programs o/p will be same.
O/P:
Parent here
5
So I think,
Inheritance: We need to override the method in child class
Abstract class: Put abstract keyword in method name and need to implement the method in child class
So Inheritance and abstract class is same regardless of abstract keyword
So we can implement abstract class using inheritance, here just method signature change classes(That's my belief).
Is there any significant difference?
Inheritance is for inheriting properties and having some of its own as well.
Abstract is to restrict from being instantiated.
Example:
Lets take Vehicle and VehiclePart. But Vehicle as such is very abstract and not complete. So we want Vehicle class abstract because we don't want to instantiate it directly. Car is more meaningful entity than Vehicle and car is a Vehicle. So car extends vehicle and it is not abstract.
abstract class Vehicle{
String name;
}
abstract class VehiclePart{
String name;
Date expiry;
}
class Car extends Vehicle{
List<VehicleParts> parts;
}
class RacingCar extends Vehicle{
}
class Gear extends VehiclePart{
int numOfGears;
}
Inheritance: We need to override the method in child class
Nope. in the above example you can see Car is inheriting properties like name from Vehicle. Overriding is optional. Like RacingCar can override methods of Car and make it a little bit custom. But basically it is getting(inheriting) some properties from base class. Like all the basic properties of a car will in Car and not in RacingCar. RacingCar will have properties specific to it.
Abstract class: Put abstract keyword in method name and need to
implement the method in child class
Nope. It is just to restrict its instantiation. Eg. We don't want to instantiate Vehicle object because there is no meaning to it. A vehicle has to be something like car, bus etc etc. It can't just be a vehicle. So we put abstract and restrict instantiation.
After java 8 you can have static and default methods in Interface. So it makes the interface much similar to abstract class.
But Still abstract class is class so we can have constructor, instance variable,
getter and setter to change the state of objects. These all functionalities not provided by interface .That is main difference between interface and abstract class after java 8.
With inheritance you don't need to override a method. Without overriding getROI in Child you could still call new Child().getROI() and get 0 as response.
If on the other hand a method is abstract, it will need to be implemented by the child as there is no default implementation.
An abstract class means you can't instantiate it directly.
new Parent()
is not allowed.
An abstract method will need to be implemented in an extended class.
Abstract Class:
Abstraction hides the implementation details and shows only the functionality to the user.
Abstraction helps to reduce the complexity of the code.
We can't create objects of an abstract class.
Inheritance:
Inheritance is the methodology of creating a new class using the properties and methods of an existing class.
Inheritance helps to improve code reusability.
We can create the object of the parent class.
These are two different concept and selections are based on the requirements.
Abstraction hide the implementation details and only show the functionality. It reduce the code complexity. Inheritance create a class using a properties of another class. It improve the code reusability.
So these are two different things for different purposes.
If this is about the implementation(coding), obviously there are differences than putting abstract keyword in the method name.
Can't implement method body in abstract methods in abstract class. But can implement method body in methods in parent class.
In inheritance, child class inherits is parents methods. Same as in abstraction also child class inherits non-abstracts methods of parent class as they are. But child class must implement all the abstract methods in parent class, otherwise child class need to be declared as abstract.
Can't create instance of abstract class.

Java: Creating Reference Type from Abstract class and interface

I am new to Java and I have read threads (here) that it is not possible to instantiate an abstract class. So, I tested it out.
The first test I did is shown below. And it seems like I can actually instantiate an abstract class and in fact, I actually have a new type which refers to the abstract class and the type is actually shared by all subclasses the extends it. This also means polymorhpism applies.
import java.util.*;
abstract class AbstractClass{
public abstract void printname();
}
class Test1 extends AbstractClass{
private String name;
public Test1(String name){
this.name = name;
}
public void printname(){
System.out.println("My name is " + name);
}
}
class Test2 extends AbstractClass{
private String saysomething;
public Test2(String saysomething){
this.saysomething = saysomething;
}
public void printname(){
System.out.println(saysomething);
}
}
class TestingApp{
public static void main(String[] args){
AbstractClass[] abstractclass_list = {new Test1("JEFFFFFF") , new Test2("Hey , say something")};
for(AbstractClass item : abstractclass_list){
item.printname();
}
}
}
Then I did another test but this time, instead of working on abstract class, I decided to create a type which refers to Interface. It seems like I can instantiate an interface as well. I can actually create a type that refers to the interface. This type is shared by all the classes that implements this interface. And polymorphism applies again.
import java.util.*;
interface AbstractInterface{
public void printname();
}
class Test4 implements AbstractInterface{
private String name;
public Test4(String name){
this.name = name;
}
public void printname(){
System.out.println("My name is " + name);
}
}
class Test3 implements AbstractInterface{
private String saysomething;
public Test3(String saysomething){
this.saysomething = saysomething;
}
public void printname(){
System.out.println(saysomething);
}
}
class TestingAbstractInterfaceApp{
public static void main(String[] args){
AbstractInterface[] abstract_list = {new Test4("Helen") , new Test3("Hey , say my name")};
for(AbstractInterface item : abstract_list){
item.printname();
}
}
}
Question:
I am sensing there is something wrong with what I am doing in my code. But I cannot quite explain how come the code still works when theoretically, it is impossible to instantiate an abstract class and interface. Am I actually instantiating an abstract class and an interface in the examples shown above ? Because this seems like exactly what I have done, as I have a new type for the abstract class and interface. Please correct me, if my logic is wrong or if I am using the wrong words.
Update:
SO I guess my misunderstanding is about type. I always thought type can only refer to normal Java classes but not abstract classes and interfaces. How does "type" actually work? Is it creating a reference?
Why do you think you are actually instantiating AbstractClass and AbstractInterface?
new Test1("JEFFFFFF") , new Test2("Hey , say something"), new Test4("Helen") , new Test3("Hey , say my name") are all instantiating concrete classes, not abstract ones.
If you refer to AbstractClass[] abstractclass_list = as proof of instantiating abstract classes, that is wrong. Here, you declare an array whose elements are of type AbstractClass, and Test1 and Test2 are (since they extend AbstractClass).
UPDATE
You could have something like this AbstractClass abs = new Test1("hey"); and what it does is it creates a new instance of class Test1, and references that instance from variable abs. abs's concrete type is Test1, but only methods declared in AbstractClass are visible on it. If you want to call methods of Test1, you would have to cast it first.
AbstractClass abs = new Test1("hey");
abs.printname(); // this is ok, and it calls `printname() implemented in Test1
abs.someTest1Method(); // this is NOT ok, someTest1Method() is not visible to abs
((Test1)abs).someTest1Method(); // this is ok, abs is cast to Test1, but would fail if abs was instantiated as 'abs = new Test2("t2")' (would throw ClassCastException)
You are not instantiating your abstract class or your interface. You are instantiating concrete classes that extend your abstract class (Test1 and Test2) or implement your interface (Test3 and Test4).
It's allowed to assign an instance of a concrete class to a variable whose type is an interface or an abstract class. In fact, it's even encouraged.
You aren't instantiating either an abstract class, nor an interface. You are just using the inherent upcasting ability from subclasses to superclasses.
Ignoring the array, and using just the first object, this would be equivalent to the implicit upcasts:
AbstractClass myObject = new Test1("JEFFFFFF");
and
AbstractInterface myObject = new Test1("JEFFFFFF");
So, in the code:
AbstractClass[] abstractclass_list = {
new Test1("JEFFFFFF") ,
new Test2("Hey , say something")};
You are instantiating objects of the concrete classes Test1 and Test2 - the Array contains references to the underlying (and common) abstract base class.
Similarly, in the second example, you are obtaining an array of interface references.
In short I would like to say that,
Parent(here, Abstract/Iterface) can refer, it's child(here, concrete class).
So here, reference variable can refer it's child class's instance.
Just note this concept in your brain, it will fix all your problem regarding, Dynamic Dispatcher, Inheritance related....!!!
You are not instantiating an abstract class and an interface,
you are instantiating some specific implementations of that abstract class and of that interface.
If you declare a list of AbstractClass or AbstractInterface you can just calls methods declared on your superclass or interface but not these declared on your specific implementations (Test1, Test2, Test3 and Test4).

how to instance generic abstract class

I am trying to profile a ann algorithm written in Java that is implemented as a generic abstract class and I cant figure out how to instance it.
Eclipse gives me error "Cannot instantiate the type KdTree" which is not very helpful. Any ideas on how to instance this class so I can test it?
Class defination and constructor:
public abstract class KdTree<T> {
private KdTree(int dimensions, Integer sizeLimit) {
this.dimensions = dimensions;
}
}
My attempt to instance it:
public class test_robo {
public void run_test()
{
KdTree<Integer> tree = new KdTree<Integer>(1,1);
}
}
link to the full code for KdTree
http://robowiki.net/wiki/User:Rednaxela/kD-Tree
First of all, you cannot instantiate an abstract class.
I saw the code in the link you provided; there are few implementations of the base class KdTree<T> already in there.
WeightedSqrEuclid
WeightedManhattan
...
If that's not what you're looking for, extend the base class and implement all those abstract methods as you wish.
You cannot instantiate an abstract class directly. The reason it is declared abstract is that it is not meant to be used by itself - you have to provide an implementation of its abstract methods first.
You need to inherit your own class from the abstract base, implement its abstract methods, and then instantiate your class. An instance of your class is automatically an instance of its abstract base.
public class ProfilerTree extends KdTree<Integer> {
public ProfilerTree(int dimensions, Integer sizeLimit) {
super(dimensions, sizeLimit);
}
...
// Implement abstract methods of KdTree<Integer> here
}
...
KdTree<Integer> tree = new ProfilerTree(1,1);
you can't instantiate an abstract class. Abstract actually means it doesn't make sense on its own so it always has to be extended and its methods implemented.
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
see http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can instantiate it by constructing an anonymous subclass, like so:
KdTree<Integer> tree = new KdTree<Integer>(1,1)
{
#Override
public void myAbstractMethodName()
{
//do something!
}
};
Otherwise, you can generate your own implementation:
private class KdTreeSub extends KdTree<Integer>
{
public KdTreeSub()
{
super(1, 1);
}
}
And later call it
public void myMethod()
{
...
KdTree<Integer> kdtree = new KdTreeSub();
...
}
The reason for this is that abstract classes are not complete classes. They are missing parts of them, usually a method. This method is marked with the "abstract" identifier:
public abstract int read();
The idea behind this is that you can construct a class that handles other parts:
public byte[] read(int len)
{
byte[] b = new byte[len];
for(int i = 0; i < b.length; i++) b[i] = read();
return b;
}
And simplify creating new classes.
The class, as it stands, was not meant to be instantiated. It's meant to store boilerplate code for concrete implementations. There are 4 of them in your link, starting with WeightedSqrEuclid.
You can either instantiate those, simply by e.g. new WeightedSqrEuclid<Integer>(1,1), or, if you want to profile the general code, write your own class extending KdTree.
However, in the latter case you should either create your subclass in the same file, or change a constructor of KdTree to at least protected. This is because, to create a subclass of this type, you need to call one of the constructors of KdTree in your implementation.

Interfaces usage

Can you have a class which implements an interface, and choose whether to use the methods in the interface during instantiation of this class? Therefore having object A which uses the interface and object B which does not use it.
Thanks
Updated:
Assuming you have a Professor class and this class implements an interface called Employer, which has employ(rAssist x) abstract method.
Now I want to instantiated 2 objects from the Professor class implementing this interface Object A - Professor can employ a research assistant and Object B - Professor cannot employ research assistants.
Can you have a class which implements an interface, and choose whether to use the methods in the interface during instantiation of this class?
No, if class C implements the interface, then all instances of C will provide the methods declared in the interface.
What you can do is something like
class MyClass implements MyInterface {
#Override
void interfaceMethod() {
System.out.println("Interface method");
}
}
and then do
MyClass x = new MyClass();
MyClass y = new MyClass() {
#Override
void interfaceMethod() {
throw new UnsupportedOperationException();
}
};
In effect, x supports the use of interfaceMethod while y does not. Note however that...
The usage of y.interfaceMethod is not prevented at compile-time, i.e. it will not be enforced by the type system.
With this solution, you are in fact creating an (anonymous) subclass of MyClass and assigning an instance of it to y.
Do you mean you want class A and Class B to implement a common Interface but you dont want to implement all methods in Class B?
An Interface in simple terms means it is sort of a contract and all the classes which implement it should follow that contract.So if you want Class B to implement the interface , Class B should also follow the same contract. But if you dont want to implement any methos you can always do this.
class ISampleInterface {
void sampleMethod();
void optionalMethod();
}
Class A implements ISampleInterface {
void sampleMethod() {
//Your Implementation
}
void optionalMethod() {
//Your Implementation
}
}
class B implements ISampleInterface {
void sampleMethod() {
//Your Implementation
}
void optionalMethod() {
throw new UnsupportedMethodException();
}
}
No, that's not the point of an Interface.
An Interface is contract that guarantees that implementations WILL implement it's signature
The idea of interface is to establish a obligation for the class that implements the interface.
If your's is a requirement, you can use the java.lang.reflect.Method reflection class to change the visibility of the method at runtime. However, this is not a clean way.
1. Interfaces were introduced in Java because Multiple Inheritance was not allowed in Java.
2. But as far as Design Pattern are concerned, following are the uses..
- To implement certain Roles.
Consider Dog a Super class, but then Pet dog and Wild dog can be interfaces, which
can be implemented by the Sub Classes of Dog class.
- Used when Behaviors keeps changing.
Consider you have a Class Drawing, and paint method() in it, now paint can be stroking, shading, etc...
You must Encapsulate such behaviors in an Interface or an Abstract class.

How to call abstract class methods to another class in java

can anybody tell me that. how can I call abstract class method to my own class in java?
thanks in advance
First of all look at you abstract class, it shall contain abstract methods and real methods. In the following sample the Foo class has an abstract method (FooMethod) and a real method (Yeee).
public abstract class Foo {
public abstract int FooMethod(int i);
public int Yeeee() {
for (int i = 0; i < 3; i++) {
int res = FooMethod(i);
// Do whatever
}
}
}
Abstract class are not meant to be directly used, so we have to inherit from them with a concrete class. The following inherits from the abstract (implementing the abstract method)
public class Bar extends Foo {
public int FooMethod(int i) {
// do something with i
}
public static void main (string [] args) {
Bar obj = new Bar();
obj.Yeeee();
}
}
Note: when in the main you call obj.Yeee() the base class method gets invoked, but in place of the abstract FooMethod, your own new implementation is used.
This is just the tip of the iceberg with abstract classes, but roughly should point you to the right direction.
Please take a good read here is a good tutorial and should give you some initial wisdom about inheritance and abstract classes.
You need to first create a subclass of the abstract class. This will then contain the methods of that abstract class. You use the "extends" keyword.
For example:
public class MyClass extends AbstractClass
{
//class content here...
}
For methods in abstract classes you need not to create the instance of the abstract class
So after importing the package in which the abstract class is present you can just call the method as below
YourAbstractClassName.methodName(args if any);
since abstract classes cant be instanciated in Java, You cant have member functions in this class and if you want to have one than their is a logical problem. However if you want to call the static methods, you can simply call them using class name, i.e.
YourClassName.fuctionName(parameters if any);
Do you mean how to implement that method in your class ?
if that is what you want to understand
then you just have to extend your class with the abstract one
for example
abstract class GraphicObject {....}
class Circle extends GraphicObject { ... }
try http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can call the method in abstract class by creating an
object of subclasss of the abstract class
or
if u want to call from the abstract class then you have to make your method static then you can call from main method like
Abstract_className.methodName()

Categories