I want to make an interface and from user point of view i want it to look clean and they can write their code with this syntax.
public class child extends parent {
#Override
public void run() {
}
}
Main is in the parent but how can one call a overriden function in parent.
Also i don't want the name "child" to be mandatory so i can't call it directly.
PS:this is the run function i want to override.
public class parent{
public static void main(String[] args) {
run();
}
}
Make Parent and run abstract. Abstract for a class means that this class cannot be directly instantiated, but can be instantiated if there is a subclass. Abstract for a method means that the method is defined in the abstract class, but is not implemented in the abstract class. Instead subclasses must provide an implementation of the abstract method or declare themselves to be abstract.
public abstract class Super {
public static void main(String[] args) {
Super s = new Sub();
s.main();
}
public abstract void run();
public void main() {
System.out.println("Calling sub class's implementation of run");
// The super class does not know the implementation of run
// but it does know that there must be an implementation to use.
run();
System.out.println("Done!");
}
}
class Sub extends Super {
#Override
public void run() {
System.out.println("sub class implementation of run");
}
}
to call overridden function of perent class use..
super.run();
EX:
public class child extends parent {
#Override
public void run() {
super.run();
}
}
what i get from you is ..u want to call child function from parent class..
For that is seams like a normal class function coz there is only relationship b/w parent-to-child no relation in child-to-parent
So u just make object of child and then call function of child class...
So your main of parent class may be look like this..
public static void main(String[] args) {
new child().run();
}
To call an overwritten function in the parent user something like one of these:
super.run();
((parent) this).run();
Do you mean you want to call the run() function defined in the parent?
public class child extends parent
{
#Override
public void run()
{
super.run(); // call parent's run() function
this.doStuff(); // call child's additional functionality
}
}
You can call super(Parent) class methods using 'super' keyword. Like this.
public class child extends parent {
#Override
public void run() {
super.run();
}
}
I suppose you are confusing between main() function and some random Main class that you are referring to. In general when it comes to inheritance you cannot call a derived class's overridden function from a base class. In that case what you do is create a base class pointer and make it point to derived class object. In that case when you use the base class pointer to invoke the function the overriden derived classs' function gets called.
I am not sure if I answered you entirely..
This might help you.. -> http://www.oodesign.com/dependency-inversion-principle.html
Not sure if i understand correctly. But parent can't know if, where and how it's protected/public methods will be overriden so it cant call the overridden implementations.
If you have to do it, you probably got your class hierarchy design wrong.
You probably need something like this.
public Parent
{
public final void run()
{
this.runChild
}
protected abstract void runChild();
}
public class Child extends Parent
{
public static void main(String[] args)
{
run();
}
protected void runChild()
{
....
}
}
I am not sure whether I am answering your question right. From what I understood is you are trying to do some thing like calling child's run from Parent. If that is the case below is the code snippet to do it.
public abstract class Parent{
public abstract void run();
public void mainMethod(){
//This automatically calls run from child
run();
}
}
And your child implementation is like as shown below.
public class child extends parent {
#Override
public void run() {
//Do the stuff you want to
}
}
public class MainClass{
public static void main(String args[]){
Parent obj = new Child();
// This inturn takes care of the rest.
obj.mainMethod();
//Some other child
obj = new Child2();
obj.mainMethod();
}
}
Hope this helps you.
Related
Example abstract class is bellow.
public abstract class Vehicle {
void maintain(String str) {
System.out.println(str);
}
}
Example concrete class is bellow.
public class Driver {
public static void main(String[] args) {
}
}
Now I need to access the maintain method without extending the Vehicle class.Is there any way to do this without using static content?
No, there isn't, because maintain is an instance method. To call an instance method, you must have an instance. You can't create an instance of an abstract class.
You can subclass it anonymously (see this tutorial), but you still need to subclass it.
You can use an anonymous inner class. I've used your example code but also defined an anstract method in Vehicle
public class AbstractTest {
public static void main(String[] args){
Vehicle v = new Vehicle() {
#Override
void myOtherAbstractMethod() {
// Do what you need here
}
};
v.maintain("foo");
}
public static abstract class Vehicle {
void maintain(String str) {
System.out.println(str);
}
abstract void myOtherAbstractMethod();
}
}
You cannot do that as abstract classes are abstract. Also in your case there's no connection between Driver and Vehicle so even if you would be able to compile that code (you won't), then ClassCastException would show up.
You must extend abstract class first, like it or not.
I have 3 classes. It seems basic question. But I can'nt find answer by googling.
public abstract class Test {
void t1()
{
System.out.println("super");
}
}
public class concret extends Test{
void t1()
{
System.out.println("child");
}
void t2()
{
System.out.println("child2");
}
}
public class run {
public static void main(String[] args) {
Test t=new concret();
t.t1();
}
}
How do I call abstract class t1 method? Since I cant create object from abstract class how do I call t1 in abstract class?
Thank you.
Either you create a concrete class which doesn't override the method, or within a concrete class which does override the method, you can call super.t1(). For example:
void t1()
{
super.t1(); // First call the superclass implementation
System.out.println("child");
}
If you've only got an instance of an object which overrides a method, you cannot call the original method from "outside" the class, because that would break encapsulation... the purpose of overriding is to replace the behaviour of the original method.
you should be able to do it using
Test test = new Test(){};
test.t1();
Abstract class means the class has the abstract modifier before the class keyword. This means you can declare abstract methods, which are only implemented in the concrete classes.
For example :
public abstract class Test {
public abstract void foo();
}
public class Concrete extends Test {
public void foo() {
System.out.println("hey");
}
}
See following tests:
public abstract class BaseClass {
public void doStuff() {
System.out.println("Called BaseClass Do Stuff");
}
public abstract void doAbstractStuff();
}
public class ConcreteClassOne extends BaseClass{
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassOne Do Stuff");
}
}
public class ConcreteClassTwo extends BaseClass{
#Override
public void doStuff() {
System.out.println("Overriding BaseClass Do Stuff");
}
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassTwo Do Stuff");
}
}
public class ConcreteClassThree extends BaseClass{
#Override
public void doStuff() {
super.doStuff();
System.out.println("-Overriding BaseClass Do Stuff");
}
#Override
public void doAbstractStuff() {
System.out.println("Called ConcreteClassThree Do Stuff");
}
}
public class Test {
public static void main(String[] args) {
BaseClass a = new ConcreteClassOne();
a.doStuff(); //Called BaseClass Do Stuff
a.doAbstractStuff(); //Called ConcreteClassOne Do Stuff
BaseClass b = new ConcreteClassTwo();
b.doStuff(); //Overriding BaseClass Do Stuff
b.doAbstractStuff(); //Called ConcreteClassTwo Do Stuff
BaseClass c = new ConcreteClassThree();
c.doStuff(); //Called BaseClass Do Stuff
//-Overriding BaseClass Do Stuff
c.doAbstractStuff(); //Called ConcreteClassThree Do Stuff
}
}
use keyword 'super' to do that
void t1()
{ super.t1();
System.out.println("child");
}
Make sure you use that in the overriden method though.
Your code seems to call t1(). However this is calling the concrete t1() because the abstract t1() has been overridden by the concrete class.
If you wish to call the abstract t1 method from main code, do not override the t1() in concrete.
Or you can create a method in the concrete class for example:
public void invokeSuperT1(){
super.t1();
}
Create an anonymous Inner class,
Abstract class:
abstract class Test{
abstract void t();
public void t1(){
System.out.println("Test");
}
}
Here is how to create anonymous inner class:
Test test = new Test() {
#Override
void t() {
//you can throw exception here, if you want
}
};
Call the class via the object created for abstract class,
test.t1();
An abstract class is used when we want that every class that inherited from our abstract class should implement that abstract method, so it is must to implement method otherwise it gives the compile-time error.
void t1()
{
super.t1; // means the parent methods
System.out.println("child");
}
For example: Bird class has method sing() and there other classes that inherited from it like the sparrow, Pigeon, Duck, so these all have sing method so we make Bird class Abstract and make the sing() method abstract in it so every child of bird that implements Bird class should have a method of sing() with its on implementation.
First Create abstarct class like as shown in link: Creating Abstract Class
Create Sub-Classs like as shown in link: Sub-class extending
Creating main method for executing this as show in link: Instanciate the subclass to access
Result as shown here: Result
So, I have an abstract class acting as a parent class, here's what I want to happen.
In abstract class:
public void run(){
while(!booleanStatement){
//do specific stuff here
}
}
In child class:
public class extends parentClass{
public void run(){
//do child stuff here effected by the while loop above
}
Is there any way to make this happen? super() maybe?
Sure. Just define an additional abstract method:
public final void run(){
while(!booleanStatement){
doRun();
}
}
public abstract void doRun();
In this scenario the subclass can't overwrite run() and is forced to provide an implementation for doRun() which does the work inside the loop.
Yes, calling super.run() will execute the parent's method.
So you can extend it by doing something like:
public void run() {
super.run();
//do child stuff
}
In abstract class:
public void run(){
while(!booleanStatement){
doStuff();
}
}
protected abstract void doStuff();
In child class:
public class extends parentClass{
protected void doStuff() {
// do something
}
Something like this will do.
Consider the following class
class A{
public void init(){
//do this first;
}
public void atEnd(){
//do this after init of base class ends
}
}
class B1 extends A{
#Override
public void init()
{
super.init();
//do new stuff.
//I do not want to call atEnd() method here...
}
}
I have several B1, B2,... Bn child classes which are already developed. All of them extend class A. If I want to add a new functionality in all of them, the best place to do so is define that in a method within class A. But the condition is that the method should always get called automatically just before the init() method of child class ends.
One basic way to do so is to again add atEnd() method call at end of init() method of child classes. But is there any other way to do this smartly ??
One way to do this is by making init() final and delegating its operation to a second, overridable, method:
abstract class A {
public final void init() {
// insert prologue here
initImpl();
// insert epilogue here
}
protected abstract void initImpl();
}
class B extends A {
protected void initImpl() {
// ...
}
}
Whenever anyone calls init(), the prologue and epilogue are executed automatically, and the derived classes don't have to do a thing.
Another thought would be to weave in an aspect. Add before and after advice to a pointcut.
Make init() final, and provide a separate method for people to override that init() calls in the middle:
class A{
public final void init(){
//do this first;
}
protected void initCore() { }
public void atEnd(){
//do this after init of base class ends
}
}
class B1 extends A{
#Override
protected void initCore()
{
//do new stuff.
}
}
The other answers are reasonable workarounds but to address the exact question: no, there is no way to do this automatically. You must explicitly call super.method().
I'm think perhaps there is not a way to do this, but I thought it worth asking. I want to do something like the following:
public class Super {
public static String print() { System.out.println(new Super().getClass().getSimpleName()); }
public Super() {}
}
public class Subclass extends Super {
public Subclass() {}
public void main(String[] args) {
Super.print();
Subclass.print();
}
}
My hope is to get the Super.print() to show "Super" and Subclass.print() to show "Subclass". I don't see how to do this from a static context however. Thanks for the help.
I'm well aware that I can do this without static methods, and that I can pass a class into each method call. I don't want to do that as that requires redefining several static methods on many subclasses.
You can simply define a separate Subclass.print() method with the desired implementation. Static methods are class scoped, so every subclass can have its own implementation.
public class Subclass {
public Subclass() {}
public static String print() {
System.out.println(Subclass.class.getSimpleName());
}
public void main(String[] args) {
Super.print();
Subclass.print();
}
}
Note that your code can be somewhat simplified - Super.class suffices instead of new Super().getClass().
Also note, that static methods are not polymorphic - Super.print() and Subclass.print() will always call the method in the respective class. This is why they are bound to a class, not an object.
If you have a large class hierarchy, you may end up with a lot of duplicated code by implementing a separate static print() in each. Instead, you could define a single non-static method to do the job:
public abstract class Super {
public final String print() {
System.out.println(this.getClass().getSimpleName());
}
...
}
Note that this method does not even need to be polymorphic - this.getClass() will always return the actual subclass token.
Note also that I declared Super as abstract - this is (almost always) good practice to follow with base classes.
You can do this with out using static methods
public class Parent {
public print(){
System.err.println(this.getSimpleName());
}
}
public class Child extends Parent {
public void main(String[] args) {
Parent p = new Parent();
p.print();
Child c = new Child();
c.print();
}
}