How do I augment the constructor of a child class? - java

I have a class that extends another class. I need to run additional code in the constructor of my child class. How do I do this?
//MyClass.class
//This is what i want to do
public class MyClass extends BaseClass {
constructor() {
super(); // EDIT (thanks)
// stuff?
}
}
Please help.

should be:
/MyClass.class
//This is what i want to do
public class MyClass extends BaseClass {
MyClass() {
super(); // no need for constructor here, just super()
// stuff?
}
}

Simply call super(). This will call the super class's constructor. See Can an abstract class have a constructor?

Related

How would I call a constructor of an abstract class inside of an extending class constructor

So for my homework I have to create an abstract class that has a few extending classes. I am stuck at one part. I can't seem to find anywhere in my lesson that tells me how to call a constructor of an abstract class. This is my teachers instructions.
MyMath's constructor will just call Homework's constructor and again have no arguments.
This is my code that I have for the abstract constructor:
public Homework(){
pagesRead = 0;
typeHomework = "none";
}
and in MyMath class I am supposed to call this constructor inside of the constructor for MyMath, I'm not sure how to do this and I cant find it in any other lessons we have been over. Any help is appreciated :)
As Stultuske already said, the super class constructor will automatically called when you create a subclass object. Alternate, you can call it explicitly by super(). Moreover, if your super class don't have a default constructor you must call it also explicitly.
public abstract class Homework
{
public Homework(int i)
{
...
}
}
public class MyClass extends Homework
{
public MyClass()
{
super(5);
}
}

Call constructor in an abstract class

Is it possible to call a constructor in a abstract class?
I read that this constructor can be called through one of its non-abstract subclasses. But I don't understand that statement. Can anybody explain this with an example?
You can define a constructor in an abstract class, but you can't construct that object. However, concrete sub-classes can (and must) call one of the constructors defined in the abstract parent class.
Consider the following code example:
public abstract class Test {
// abstract class constructor
public Test() {
System.out.println("foo");
}
// concrete sub class
public static class SubTest extends Test {
// no constructor defined, but implicitly calls no-arg constructor
// from parent class
}
public static void main(String[] args) throws Exception {
Test foo = new Test(); // Not allowed (compiler error)
SubTest bar = new SubTest(); // allowed, prints "foo"
}
}
You can't call an abstract class constructor with a class instance creation expression, i.e.
// Invalid
AbstractClass x = new AbstractClass(...);
However, in constructing an object you always go through the constructors of the whole inheritance hierarchy. So a constructor from a subclass can call the constructor of its abstract superclass using super(...). For example:
public class Abstract {
protected Abstract(int x) {
}
}
public class Concrete {
public Concrete(int x, int y) {
super(x); // Call the superclass constructor
}
}
As constructors of abstract classes can only be called within subclass constructors (and by chaining one to another within the same class), I typically make them protected... making them public would serve no purpose.
The normal rules apply if you don't specify a super(...) or this(...) call in a concrete subclass constructor - it's equivalent to a super(); statement at the start of a constructor, calling a parameterless constructor in the superclass... so there'd have to be such a constructor.
In this example Java program, we have an abstract class Servidor, which has one parametric constructor, which accepts name. Subclass provides that name to superclass while creating concrete instance of Servidor and overriding abstract method start(). Since this program compile and run fine you can definitely say abstract class can have constructors in Java.
public class AbstractConstructorTest {
public static void main(String args[]) {
Servidor Servidor = new Tomcat("Apache Tomcat");
Servidor.start();
}
}
abstract class Servidor{
protected final String name;
public Servidor(String name){
this.name = name;
}
public abstract boolean start();
}
class Tomcat extends Servidor{
public Tomcat(String name){
super(name);
}
#Override
public boolean start() {
System.out.println( this.name + " started successfully");
return true;
}
}
Output:
Apache Tomcat started successfully
You can obviously do something like:
public class ConcreteClass extends AbstractClass {
public ConcreteClass(){ // concrete class constructor
super(); // abstract class constructor
}
}
A constructor of an abstract class can be used only inside constructors of concrete classes inheriting from it.
Abstract and Concrete classes are something like Generalization and Specialization in Java and can be executed using inheritance. Let me explain with a plain and simple example. Say we have a class "DBConnector". It seems to be more generalized class and its meaning less to instantiate the class (which DB you are connecting to, driver vary for each DB right). Hence we can make DBConnector as abstract. That is the reason why we cannot basically instantiate Abstract classes.
Now we can create different concrete classes for each database extending the behavior of our concrete class like "OracelDBConnector", "MySQLDBConnector" etc., As we inherit the properties of abstract class into concrete class, we initialize the abstract class properties ideally using abstract class constructor using concrete class constructor using super(parameter list).
Thanks,
JK

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()

How to call a method in a class hierarchy?

I have this super class which extends from another class
public abstract class AbstractDOEMessageFinderAction extends BasicObjectFinder {
public Object performBasicSearch() {
// works fine because getQuery is defined in BasicObjectFinder
return getQuery();
}
The other class is ISIRFinderAction which extends from AbstractDOEMessageDashboardAction
ISIRFinderAction extends AbstractDOEMessageDashboardAction {
// My aim is to make sure this method works so that I will make
// the super class's performBasicSearch() method abstract.
public Object performBasicSearch() {
// this one doesnt even compile but it extends AbstractDOEMessageDashboardAction
// which in turn extends BasicObjectFinder
return getQuery();
}
}
Am I missing something? Why is getQuery not working. I thought it would search it in the class hierarchy.
The second class extends AbstractDOEMessageDashboardAction not AbstractDOEMessageFinderAction.
Does AbstractDOEMessageDashboardAction also extend BasicObjectFinder?
(Note, AbstractDOEMessageDashboardAction is ofcourse not the same as AbstractDOEMessageFinderAction).

Java: why does extending need an empty constructor?

I have classes SearchToUser and getFilesToWord. GetFilesToWord must inherit SearchToUser fields. Extending works if an empty construction in SearchToUser-class, otherwise:
cannot find symbol
symbol : constructor SearchToUser()
location: class SearchToUser
public class GetFilesToWord extends SearchToUser{
^
1 error
make: *** [all] Error 1
I cannot understand why the empty constructor is required for extending.
[Added]
-- ALERT ERRR! USE COMPOSITION! Left as an "bad" example --
Composition VS Inheritance
It works but can you spot some weaknesses? Could I make the searchTerm private, create public method for it, create object of SearchToUser for the parameter in GetFilesToWord?
SearchToUser.java
public class SearchToUser {
public static GetFilesToWord geader;
public static String searchTerm;
SearchToUser(String s){
searchTerm=s.trim().toLowerCase();
files=geader.getFilesToWord(s);
}
...
}
GetFilesToWord.java
public class GetFilesToWord extends SearhToUser{
public GetFilesToWord(){super(SearchToUser.searchTerm){
...
}
The superclass doesn't need an empty constructor specifically. The subclass simply needs to call a constructor in the superclass. If the superclass has a public or protected no-arg constructor, this is called automatically, otherwise you need to be explicit.
Default constructor
public class Super {
}
public class Sub extends Super {
}
Here, Super specifies no constructor so one is added. Same for Sub. The above really looks like this:
public class Super {
public Super() {
}
}
public class Sub extends Super {
public Sub() {
super();
}
}
Explicit no-arg constructor
public class Super {
public Super() {
}
}
public class Sub extends Super {
}
This is legal. A constructor is added to Sub that calls Super's default constructor.
Explicit constructor with arguments
public class Super {
public Super(int i) {
}
}
public class Sub extends Super {
}
This is a compile error like you have. Because Super has a constructor, no no-arg constructor is added automatically by the compiler. The way to deal with this is:
public class Super {
public Super(int i) {
}
}
public class Sub extends Super {
public Sub() {
super(0); // <-- explicit constructor call
}
}
Technically it's not... but if you don't explicitly provide a constructor in GetFilesToWord that explicitly calls the superclass constructor, Java will automatically insert a call to the no-argument superclass constructor. But if there isn't a no-argument superclass constructor, Java doesn't know what values to provide for the argument, and it can't automatically insert the call. You then have to manually call the superclass constructor with whatever values are appropriate.
The reason there needs to be a call to the superclass constructor at all is that, to put it one way, the operation of constructing a GetFilesToWord includes within it the operation of constructing a SearchToUser. For example, if you had instance variables in SearchToUser, they would need to be initialized when you create a GetFilesToWord as well as when you create just a plain SearchToUser.

Categories