Java OO Concept - java

Good day!
I am reviewing the Java OO concept.
And wrote the following codes:
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
dog.eat();
dog.sleep();
}
}
abstract public class Animal {
private int age;
public Animal (){
age = 1;
}
public Animal (int age){ //How can I call this constructor?
this.age = age;
}
public void eat(){
System.out.println("Eat");
}
abstract public void sleep();
}
abstract public class Canine extends Animal{
abstract public void roam();
}
public interface Pet {
public String petName = null; //i want the pets to have a variable petName.
public void trick();
}
public class Dog extends Canine implements Pet{
public void roam(){
System.out.println("roam");
};
public void sleep(){
System.out.println("sleep");
};
public void eat(){
System.out.println("Eat Dog");
};
public void trick(){
System.out.println("trick");
}
}
I have several questions as follows:
How can I call the Animal Overloaded constructor?
How can I use the variable petName in the PET Interface?
Am I doing the concept of OO correctly? What rules am I violating?
Thank you in advance.

Subclasses will call the super constructor from within their own constructor using super(...) as the first line!
Interfaces cannot have variables or state - only methods!
You have a sound concept, but your code would not compile (because of item 2 above).
Some solutions:
public interface Pet {
String getName();
void trick();
}
Now the Dog class (or any class that implements Pet) will have to implement Pet.getName(). Give the Dog class a field of type String called 'name' and return it from Dog.getName().
public abstract class Canine extends Animal {
public Canine(int age) {
super(age); // pass the age parameter up to Animal
}
...
}
public class Dog extends Canine implements Pet {
private final String name;
public Dog(String name,int age) {
super(age); // call the age constructor
this.name=name;
}
public String getName() { return name; }
... rest of class ...
}
Each subclass (esp. the abstract ones) will need to provide matching constructors for all parent class constructors you want to call! (So I added the age parameter to the Canine constructor so that Dog could pass an age argument to it.

check out this ,it might help you,
http://www.roseindia.net/java/beginners/constructoroverloading.shtml
http://www.jchq.net/certkey/0602certkey.htm

Calling either constructor is calling an overloaded constructor: both constructors use the same name. To call the constructor that takes an int, call dog = new Dog(1);.
The class Dog implements Pet, so it will have a public field petName (is it super.petName?).
I don't see any fundamental errors.

1) you can call argumented contructor as" this(20);"
Example of explicit this constructor call
public class Point {
int mx;
int my;
//============ Constructor
public Point(int x, int y) {
mx = x;
my = y;
}
//============ Parameterless default constructor
public Point() {
this(0, 0); // Calls other constructor.
}
. . .
}super(...) - The superclass (parent) constructor
An object has the fields of its own class plus all fields of its parent class, grandparent class, all the way up to the root class Object. It's necessary to initialize all fields, therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly.
The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor. The following is the equivalent of the constuctor above.
//============ Constructor (same as in above example)
public Point(int x, int y) {
super(); // Automatically done if you don't call constructor here.
m_x = x;
m_y = y;
}Why you might want to call super explicitly
Normally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
You want to call a parent constructor which has parameters (the automatically generated super constructor call has no parameters).
There is no parameterless parent constructor because only constructors with parameters are defined in the parent class.

A call to the parent constructor is super(); in your case it would be super(12); for example. Note that a call to a constructor (either this() or super() must be the first statement. Note that you can only go up one level, so to call the constructor in Animal, you'd have to code that into Canine and not Dog.
public Dog(int age)
{
super(age); //this will invoke Canine's overloaded constructor
}
//You must now provide the overloaded constructor in Canine which invokes
//the overloaded constructor in Animal
public Canine(int age)
{
super(age); //this will invoke Animal's overloaded constructor
}
You may access the value of Pet.petName as, well, Pet.petName. This is because Interfaces can only have methods (which are implicitly public) and constants (which are implicitly public static final). You could use this.petName but it's pointless (and potentially confusing). You cannot set the value of petName anywhere else, ever since it's final, even if you don't declare it to be.
However in this case, declaring the name as part of the interface doesn't make sense since it's not constant. It should be a part of some abstract or concrete class so that it can be set per instance of Pet. You should instead define a getter (and maybe a setter) for Pet -
public String getName();
public String setName(String name);
these will force implementing classes to provide some sort of implementation to get and set the name for a Pet without enforcing how that name is stored inside of that class.

How can I call the Animal Overloaded constructor?
You need to chain it.
abstract public class Canine extends Animal{
public Canine(int age) {
super(age);
}
// ...
}
and
public class Dog extends Canine implements Pet{
public Dog(int age) {
super(age);
}
//...
}
How can I use the variable petName in the PET Interface?
Pet.petName. If a class implements such an interface, then the class can refer to those constants without a qualifying class name like this: petName
Am I doing the concept of OO correctly? What rules am I violating?
Interface constants

Related

Is it inheritance that make my compilation error?

Why the code is not compiling? so what is the reason why it is not compiling can someone state or elaborate it for me?
class Pet{
public Pet(int age){
System.out.print("Pet age: " + age);
}
}
public class Cat extends Pet{
public Cat(){
System.out.print("Cat");
}
public static void main(String[] args) {
new Pet(5);
}
}
Error Log:
Cat.java:7: error: constructor Pet in class Pet cannot be applied to given types;
public Cat(){
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
The Cat constructor needs to call the constructor of the superclass Pet with an age argument.
For example something like this:
public Cat(int age){
super(age)
System.out.print("Cat");
}
The error clearly says that you dont have default constructor in your parent class.
Every Java class has an empty constructor by default. but when you create a Parameterised constructor by yourself, It replaces the empty constructor.
To fix the error, either create an empty constructor in your Parent class, Or Call the parameterised constructor from your parent class.
This is the modified version of your code that should work.
class Pet{
public Pet(int age){
System.out.print("Pet age: " + age);
}
}
public class Cat extends Pet{
public Cat(int age){
super(age);
System.out.print("Cat");
}
public static void main(String[] args) {
new Cat(5);
}
}
Your Cat class inherits from the Pet class.
Pet class requires an integer in its default constructor.
Therefore the default constructor of Cat must call the Pet constructor with an integer parameter.
Alternatively, you can define a default constructor in Pet which does not take in an integer.
You should be able to call the parent constructor as such:
public class Cat extends Pet{
public Cat(){
super(3);
System.out.print("Cat");
}
}
When call is made to the Cat() constructor of Cat class, it will internally call the default constructor of parent class Pet. While when you declared the parameterized constructor for Pet class, it has no more default constructor exist there.
In order to fix it, you need to explicitly declare the default constructor for parent class Pet. Or explicitly call parameterized constructor of parent class.
In Cat constructor parent constructor(Pet) will be called. So you either you need to defined default no argument constructor in Pet class or call super(5) in Cat default constructor.
Default constructor missing in Pet.since you are extending Pet in Cat you need a super constructor to avoid this
class Pet{
public Pet(){};
public Pet(int age){
System.out.print("Pet age: " + age);
}
}
public class Cat extends Pet{
public Cat(){
System.out.print("Cat");
}
public static void main(String[] args) {
new Pet(5);
}
}
you have to call super class with an integer parameter. when main method call new object it calls Cat constructor it will search super class no arg constructor. but there is no no arg constructor so either need to added super class default constructor or call the super with parameter. sample code is below.
class Pet{
public Pet(int age){
System.out.print("Pet age: " + age)}}
public class Cat extends Pet{
public Cat(){
super(5);
System.out.print("Cat");}
public static void main(String[] args) {
new Pet(5);}}

How to return the value of a super variable?

I'm writing program that demonstrates the use of inheritance and I have created a variable using the super() keyword. I am now trying to place the value of that variable into a new method that calls it so that I can call that method in my main method to use its value within other classes.
Here is the relevant code:
Food class (super class)
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
Meat class (sub class with super keyword)
public class Meat extends Food
{
public Meat() {
super("Meat");
}
public String getName() {
return //get super() value??;
}
}
Main class
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
Meat meatExample = new Meat();
System.out.println("************Wolf\"************");
System.out.println("Wolves eat " + meatExample.getName());
}
}
Any help is appreciated, thanks.
You could just do
public String getName() {
return super.getName();
}
Although you don't even need to override the method in the first place, because you declared the field name in super class to be public which means it can be accessed from anywhere.
Don't override public String getName() in Meat class.
The inheritance allows to inherit public and protected methods of Food in all subclasses of Food, therefore in Meat.
So Meat which IS a Food has by definition this behavior :
public String getName() {
return name;
}
which returns the name field stored in the parent class.
Overriding a method in subclass to write exactly the same code than in the parent method is useless and should not be done because it is misleading. A person which reads the code will wonder : why having overrided the method in the child class if it does the same thing than the parent class ?
Edit
Besides, if you want to access a field declared in a super class from a subclass, you should :
provide a public getter in the super class if the field is private. Here :
public String getName() {
return name;
}
use directly the field in the subclass if the field has the protected modifier.
As a general rule, you should avoid declaring instance fields with the modifier public because by default properties of a object should be protected and you should provide methods to modify the field only if needed.
So, declaring your Food class like that seems more suitable :
public class Food {
//field that stores the name of the food
private String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
In your Meat class, imagine you would like to add an additional information in the string returned by getName(), you could override it and why not using the field from the super class :
public class Meat extends Food {
public Meat() {
super("Meat");
}
#Override
public String getName() {
return super.getName + "(but don't abuse it)";
}
}
Here overriding the method is helpful because the behavior of the method in the child class differs from which one definedin the super class.
Simply write:
public String getName() {
return name;
}
This is because when searching for a variable named name, Java proceeds in this order:
Local variables (none)
Current class's fields (none)
Superclass's fields (found)
Super-super-class's fields (etc.)
However, you didn't need to override getName() in the subclass in the first place. If you didn't define it, then it would inherit the superclass's implementation, which corresponds exactly to the behavior you wanted. Thus you were doing extra work for no gain.
The other answers showed you how to do what you want.
But you should't do it (in real life projects)!
The most important principle in object oriented programming is encapsulation (aka information hiding). This means that the internal structure of a class should not be visible or accessible to the outside.
Therefore all member variables should be private.
Also you should avoid setter/getter methods since they just redirect the access. (except the class is a DTO without any logic of its own).
Since food class has the method getName declared as public do
public String getName() {
return super.getName();
}

Java Extending a class and setting values

Animal Base Class
public class Animal
{
protected String pig;
protected String dog;
protected String cat;
public void setPig(String pig_)
{
pig=pig_;
}
public void setCat(String cat_)
{
cat=cat_;
}
public void setDog(String dog_)
{
dog=dog_;
}
}
AnimalAction Class
public class AnimalAction extends Animal
{
public AnimalAction(String pig, String cat, String dog)
{
super.pig = pig;
super.cat = cat;
super.dog = dog;
}
}
Would this be the correct way to set protected variables? Is using protected variables the correct way to do this? Is there a more professional OO way to do?
You can use private variables instead of protected. This will be more apt.
You can use the constructor to set the value of the super class.
Edited:
public class Animal{
private String pig;
private String dog;
private String cat;
public Animal(String pig,String dog,String cat){
this.pig=pig;
this.dog=dog;
this.cat=cat;
}
}
public class AnimalAction extends Animal
{
public AnimalAction(String pig, String cat, String dog)
{
super(pig,dog,cat);
}
}
You should be able to use this.pig etc, since you inherited the protected members. You could also actually call the public setPig(...) methods.
There is nothing wrong in using protected member variable and then inherit them in subclass .
But If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later.
By providing protected member variables you are just coupling tight between you subclass and superclass.
The less your member variables can be seen outside the class, the better. I would make the class variables private and make the getters public (or as required) & the setters protected.
There's no need to use the super prefix, or any other prefix, to access protected variables.
BTW - I disagree with Thomas on one point - do not call the setter methods of the superclass in your constructor. Using non-final setters in a constructor may have ugly effects if a subclass overrides them. Then they could be called on an incompletely constructed object. But you should consider making your setters final if you don't mean them to be overridden.
The principle of "design for inheritance or forbid it" is explained in the Effective Java book by Joshua Bloch.
Your example is quite confusing, but it would work. I'll give another example:
// use capitals for classes/interfaces/enums, lower case for methods/fields.
public class Animal
{
protected String name;
protected int numberOfFeet;
public Animal(String name)
{
this.name = name;
}
public void setNumberOfFeet(int numberOfFeet)
{
this.numberOfFeet = numberOfFeet;
}
}
public class Dog extends Animal
{
public Dog()
{
super("dog"); // call the constructor of the super class.
// because Dog extends Animal and numberOfFeet is protected, numberOfFeet becomes part of "this" class.
this.numberOfFeet = 4;
}
}
//Now you can create instances of Animal like:
Animal bird = new Animal("bird");
bird.setNumberOfFeet(2);
//Or use Dog to create an animal "dog" with 4 feet.
Animal dog = new Dog();
//after an accident
dog.setNumberOfFeet(3);

super() in Java

Is super() used to call the parent constructor?
Please explain super().
super() calls the parent constructor with no arguments.
It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).
Also it can be used to call methods from the parent. I.e. super.aMethod()
More info and tutorial here
Some facts:
super() is used to call the immediate parent.
super() can be used with instance members, i.e., instance variables and instance methods.
super() can be used within a constructor to call the constructor of the parent class.
OK, now let’s practically implement these points of super().
Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.
Program 1
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
Output:
200
200
Now check out program 2 and try to figure out the main difference.
Program 2
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
Output:
100
200
In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.
OK, now check out the difference between program 3 and program 4.
Program 3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
Output:
200
Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.
Program 4
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
Output:
100
200
Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super()
Yes. super(...) will invoke the constructor of the super-class.
Illustration:
Stand alone example:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)
There is also a super keyword, that you can use in methods to invoke a method of the superclass
A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.
public class Alien{
public Alien(){ //Default constructor is written out by user
/** Implementation not shown…**/
}
}
public class WeirdAlien extends Alien{
public WeirdAlien(){
super(); //calls the default constructor in Alien.
}
}
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
I would like to share with codes whatever I understood.
The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-
1. Use of super with variables:
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:-
Maximum Speed: 120
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output:-
This is student class
This is person class
3. Use of super with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:-
Person class Constructor
Student class Constructor
What can we use SUPER for?
Accessing Superclass Members
If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName();
Invoking Superclass Constructors
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Look at the code below:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class
of the top layer in the inheritance tree.And then all the way down the inheritance tree.The
reason why this is possible to happen is that the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.If there's no non-argument constructor
in the superclass and the subclass doesn't explicitly say which of the constructor is to
be executed in the superclass,you'll get a compile-time error.
In the above code,if we want to create a Wolf object successfully,the constructor of the
class has to be executed.And during that process,the two-argu-constructor in the Animal
class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same
class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature
class and the non-argu-constructor again implicitly invokes the empty constructor in the Object
class.
Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :
public MyClass(int a) {
this(a, 5); // Here, I call another one of this class's constructors.
}
public MyClass(int a, int b) {
super(a, b); // Then, I call one of the superclass's constructors.
}
super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.
Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :
public String toString() {
int hp = this.hitpoints(); // Calls the hitpoints method in this class
// for this object.
String name = super.name(); // Calls the name method in the superclass
// for this object.
return "[" + name + ": " + hp + " HP]";
}
super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.
This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .
If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.
Here is an example of this:
class A {
A() {
System.out.println("Constructor A");
}
}
class B extends A{
public B() {
System.out.println("Constructor B");
}
}
class C extends B{
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
The above would output:
Constructor A
Constructor B
Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Usage of Java super Keyword
super can be used to refer to the immediate parent class instance variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor.
There are a couple of other uses.
Referencing a default method of an inherited interface:
import java.util.Collection;
import java.util.stream.Stream;
public interface SkipFirstCollection<E> extends Collection<E> {
#Override
default Stream<E> stream() {
return Collection.super.stream().skip(1);
}
}
There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass:
public class OuterInstance {
public static class ClassA {
final String name;
public ClassA(String name) {
this.name = name;
}
public class ClassB {
public String getAName() {
return ClassA.this.name;
}
}
}
public static class ClassC extends ClassA.ClassB {
public ClassC(ClassA a) {
a.super();
}
}
public static void main(String[] args) {
final ClassA a = new ClassA("jeff");
final ClassC c = new ClassC(a);
System.out.println(c.getAName());
}
}
Then:
$ javac OuterInstance.java && java OuterInstance
jeff

Doubt in abstract classes

public abstract class Person {
private String name;
public Person(String name) {
this.name = name;
System.out.println("Person");
}
public String getName() {
return name;
}
abstract public String getDescription();
}
public class Student extends Person {
private String major;
public Student(String name, String major) {
super(name);
this.major = major;
}
public String getMajor() {
return major;
}
#Override
public String getDescription() {
return "student" + super.getName() + " having" + major;
}
}
public class PersonTest {
public static void main(String[] args) {
Person person = new Student("XYZ", "ABC");
System.out.println(person.getDescription());
}
}
Ques: We cannot create objects of abstract classes, then why Person Constructor has been invoked, even its an abstract class?
Because it's still a class and its constructor is invoked as a part of the object instantiation. The fact that it is abstract doesn't have anything to do with this.
Ques: We cannot create objects of
abstract classes, then why Person
Constructor has been invoked, even its
an abstract class?
If a class is declared abstract, no objects of that class can be created. That DOESNOT mean you cannot create objects of its subclasses.
You can have references(of type abstract class) refer to a subclass(non abstract) object.
Person person = new Student("XYZ",
"ABC");
And in order to construct a Student object, you need to have the "person" parts of the student initialized, thats what exactly the constructor of the abstract super class is called for.
What you can't do is to create an instance of an abstract class.
As a Student is 'partly' a Person super(...) initializes the 'Person part' of the student, it does not create a Person.
I hope you understand what I try to say
The constructor is just a method like others. And you are calling it explicitly from your child class' constructor with:
super(name);
The Person constructor is invoked from the Student class. From the Java tutorials
An abstract class is a class that is
declared abstract—it may or may not
include abstract methods. Abstract
classes cannot be instantiated, but
they can be subclassed.
An abstract class can have constructors - they cannot be invoked directly, but only as part of constructing a subclass instance, via a call to super() in the subclass constructor.
One cannot make an instance of an abstract class but subclasses can call super(name);. Even though it is a constructor, it is just another method.
The Abstract class is a part of your overall concrete class. An Abstract class is a class that is allowed to defer many parts to its concrete implementations but it must still initialize itself.
As such it has a constructor and as such the constructor with any parameters it requires to set itself up.
When you call the super(...) method from your Student class you are explicitly calling the constructor in the Person template class. The super() call must be in the first line of the Person constructor so if your person class wishes to override the defaults set up by the Person() constructor, then you have that option. But exactly one person constructor MUST be invoked when you extend a class (Abstract or concrete).

Categories

Resources