How to access values of fields from base class? - java

I want to access fields of a class from base class in Java. I can do it in dot net.
see the example:
public class a{
// here I want to read the value of name or f1 or f2 or every other field values from derived classes
}
public class b extends a{
public string name;
}
public class c extends a{
public string f1;
public string f2;
}
How to do it?

You cannot read the fields your class doesn't own without explicitly naming the subclass. So, this is doable as follows:
((c)this).f1;
However, doing this would be a bad code smell: you are now tying an abstraction embodied by a to one of its specific implementations/extensions. You should better rethink your design.
An important note on code conventions
In Java it is a must that you name your classes using CamelCase and packages using lowercase, otherwise some quite bad name-resolution anomalies can happen. Not to mention any Java user getting totally lost reading your code.

You really don't want to do that as it defeats the idea of inheritance.
You can, however set up abstract functions that are implemented by derived classes. That's good programming style. Those functions can access member data in the derived and base classes.
Doing things like (i) using reflection and(ii) casting to derived classes are hacks and should be avoided. The reason being that changing a derived class should not trigger the necessity for changes in a base class.

What you should do in this case is to define abstract methods in your class a, which class b and c has to implement. You can then call these methods from a to obtain the values set by b and c.
public abstract class a{
// here I want to read the value of name or f1 or f2 or every other field values from derived classes
abstract String getName();
abstract String getF1();
abstract String getF2();
}
public class b extends a{
private String name;
#Override
public String getName() { return name; }
#Override
public String getF1() { return null; }
#Override
public String getF2() { return null; }
}
public class c extends a{
public String f1;
public String f2;
#Override
public String getName() { return null; }
#Override
public String getF1() { return f1; }
#Override
public String getF2() { return f2; }
}

Related

What is the best way to reduce the number of extends to have as less class possible in Java?

So to be short I need a class License that need to be extends into two sub classes, let's call them A and B.
License :
public abstract class License{
}
A :
public class A extends Licence{
Date valid;
Date expire;
}
B :
public class B extends Licence{
}
But both of them can also be a different type according to the age of the User (child, young Adult, Adult, Senior). I would have used an enum but in the case of the child it needs to have a tutor(User) to have a license.
So the only way possible I see is to extends both 4 for every type.
Example of what I don't want:
//extends of A
public class AChild extends A{
User tutor;
}
public class AYoungAdult extends A{
}
public class AAdult extends A{
}
public class ASenior extends A{
}
//extends of B
public class BChild extends B{
User tutor;
}
public class BYoungAdult extends B{
}
public class BAdult extends B{
}
public class BSenior extends B{
}
The problem is not huge I just want a cleaner way to do it. :)
You can explain me with code or Class diagram if its easier.
Inheritance:
When we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. In doing this, we can reuse the fields and methods of the existing class.
Composition
The composition also provides code reusability but the difference here is we do not extend the class for this.
Inheritance
Composition
We define the class which we are inheriting(super class) and most importantly it cannot be changed at runtime
We only define a type which we want to use and which can hold its different implementation also it can change at runtime. Hence, Composition is much more flexible than Inheritance.
We can only extend one class, in other words more than one class can’t be extended as java does not support multiple inheritance.
It allows to use functionality from different class.
Inheritance cannot extend final class.
Composition allows code reuse even from final classes.
It is an is-a relationship.
It is a has-a relationship.
Inheritance should only be used when subclass ‘is a’ superclass. Don’t use inheritance to get code reuse. If there is no ‘is a’ relationship, then use composition for code reuse. Classes should achieve polymorphic behavior, design flexibility, and code reuse by their composition rather than inheritance from a base or parent class.
Example:
Inheritance:
class Person {
String title;
String name;
int age;
}
class Employee extends Person {
int salary;
String title;
}
Composition:
class Person {
String title;
String name;
int age;
public Person(String t, String n, int a) {
this.title = t;
this.name = n;
this.age = a;
}
}
class Employee {
int salary;
private Person person;
public Employee(Person p, int s) {
this.person = p;
this.salary = s;
}
}
Here the Employee class has a Person. It does not inherit from Person but instead gets the Person object passed to it, which is why it "has a" Person.
In your case:
Using Composition:
import java.util.Date;
class License{
String type;
String name;
public License(String t, String n) {
this.type = t;
this.name = n;
}
}
class A{
Date valid;
Date expire;
private License license;
public A(License l, Date v, Date e) {
this.license = l;
this.valid = v;
this.expire = e;
}
}
What if Licence and A both declared 'color'?
Should Documents.color return "Red" or "Blue"? Under composition this ambiguity is better handled:
class Documents {
String color;
public Documents(License li, A aa) {
this.color = li.color;
}
}
The Documents object is composed as an Licence and a class A. The Color behavior is taken from class Licence. This explicit composition removes ambiguity among other things and you'll encounter fewer bugs.
General rule of thumb: Before using inheritance, consider if composition makes more sense.
Reason: Subclassing usually means more complexity and connectedness, i.e. harder to change, maintain, and scale without making mistakes. Prefer composition over inheritance.
Okay so I found a solution.
So first I extended User to all of the age categories and then I made an interface for YoungAdult, Adult and Senior named ITutorable:
public interface ITutorable {
}
Example of implements ITutorable:
public class Adult extends User implements ITutorable{
}
And in License I made two constructors. One for just a User ITutorable and the other a Child and a ITutorable like that:
public abstract class License {
public License(ITutorable user) {
}
public License(Child user,ITutorable tutor) {
}
}
If you have a better idea, let me know, I would love to hear it!
Otherwise thanks a lot!
Java 8+ supports default methods in interfaces.
This could supplement your interface solution as follows:
public interface LicenseBearer {
default LicenseBearer getResponsiblePerson() { return this; }
}
This will always return the class which implements the LicenseBearer interface, unless you #Override the method, e.g. for your implementing Child class. Also, the License classes would no longer have to care, that the supplied Child has a Tutor. You could thus move the responsibility for the Child-Tutor-relationship out of the License class' domain.
You would then have an abstract class Person implements LicenseBearer from which you could derive - if necessary - your other Person-classes, of which only Child has a special behaviour regarding to Licenses:
public class Child extends Person {
Person tutor;
private Child() { /* No Child without a tutor Person allowed */ }
public Child(Person tutor) {
this.tutor = tutor;
}
#Override
public LicenseBearer getResponsiblePerson() {
return this.tutor;
}
}

Design pattern needed for enforcing static methods

Okay, I want to start off my question with an example of what I'd basically like to do, though it's not working this way.
I want to have an interface IDog that enforces its implementations to have some methods. I also want an superclass AbstractDog implements IDog to give basic attributes and methods to all Dog classes. Then I want to have Subclasses like Poodle extends AbstractDog. My problem here are static methods - I basically want each subclass of AbstractDog to have a different static method but I want to be able to enforce this method from IDog.
So my naïve (and wrong) implementation would be:
public interface IDog {
String getName(); // every dog instance should be able to call name
static String getDescription(); // every dog class should be able to get its description
}
public abstract class AbstractDog implements IDog {
private String name; // every dog instance will have this
public AbstractDog(String name) {
this.name = name;
}
#Override
public String getName() {
return this.name; // every dog instance can call this
}
}
public class Poodle extends AbstractDog {
private static String description = "It's a poodle!"; // all Poodles have the same description
public Poodle(String name) {
super(name);
}
#Override // from IDog
public static String getDescription() {
return description;
}
}
Now, as I said, this is not correct because the AbstractDog class would need a static abstract method getDescription() and IDog needs an implementation of its method and it can't be overridden.
I want to know, if there is a Design pattern which matches my problem: enforcing a set of classes (which could or should have an intermediate superclass) to implement a (different!) static method.
One possibility I have discovered, but I'm not sure if it may be useful or even adequate, would be the use of an enum DogType and then just having a class Dog with a DogType attribute:
public enum DogType {
Poodle("This is a poodle."), Havanese("This is a Havanese.)";
private String description;
private DogType(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
public class Dog {
private String name;
private DogType dogType;
public Dog(String name, DogType dogType) {
this.name = name;
this.dogType = dogType;
}
public String getName() {
return this.name;
}
public String getDescription {
return this.dogType.getDescription();
}
}
However, this "workaround" loses an ability over my initial idea: I now can't additional functionalities to only one dog class like an instance method void prance() which should only be accessible to Poodle.
Many topics regarding similar questions have refered to the Factory pattern, but I'm not sure how it fits my problem because I don't necessarily need a constructing method. And as the number of dog races rises my code would become very confusing I think. Or maybe I just didn't get how the Factory should be used correctly in my case.
Interfaces are enforced behaviours. Classes are used to specify properties. Static methods get hidden. They are not over-ridden by subclasses. So if you have static methods in your subclasses, but your object reference is of supertype class, then your static method from superclass is invoked. This is class Method hiding, happens with static methods.
I want to know, if there is a Design pattern which matches my problem:
enforcing a set of classes (which could or should have an intermediate
superclass) to implement a (different!) static method.
Sorry. Static methods and inheritance don't go hand in hand.
I now can't additional functionalities to only one dog class like an
instance method void prance() which should only be accessible to
Poodle.
You could introduce a interface Prancable with method void prance().
public interface Prancable{
void prance();
}
public class Poodle extends Dog implements Prancable{
#Override
public void prance(){
System.out.println("My Poodle can prance.");
}
}
You can proceed in this manner for specific methods that add behaviour to different dog breeds.
This is a code smell, there is likely a better way to do it.
If the static method will always return the same thing for all objects of the class, you should just make it a regular get method.
#Override \\ from IDog
public String getDescription() {
return "This is a poodle";
}
If the static variable may be changed then make a new object that holds this class-wide state and give it to each class in the constructor.
ex.
// StringState is a new class that holds a string and has a set and get method
StringState desc = new StringState("original description");
IDog dog1 = new Poodle(desc);
IDog dog2 = new Poodle(desc);
// prints original description
System.out.Println(dog1.getDescription());
System.out.Println(dog2.getDescription());
desc.set("New description");
// prints new description, since both objects share the same
// StringState,changing it here changes it in all of them.
System.out.Println(dog1.getDescription());
System.out.Println(dog2.getDescription());

Java Abstraction and Interfaces

It's been a rather long time since I've messed around with Java Abstraction and/or Interfaces, but I'm coming back to it now for a project and something is getting on my nerves. Below is a snippet of my code.
public class A {
private static String name = "None";
private static String description = "No description";
public A() {}
public A(User user) {
user.setData(this);
}
public static String getName() {
return name;
}
public static String getDescription() {
return description;
}
}
public class B extends A {
private static String name = "B";
private static String description = "This is B";
public B() {}
public B(User user) {
super(user);
}
}
public class User {
private A a;
public void setData(A a) {
this.a = a;
}
public A getData() {
return a;
}
}
When I use B.getName() I expect it to return "B" but it's instead returning "None".
Now I'm obviously doing something wrong, and searching around didn't help a bit. I'm fairly positive that this is possible someway, unless I'm getting confused with another language.
Could someone please point me in the right direction? Thanks.
You called the getName method on the class B. B doesn't have a static method called getName, so it looks for it in the superclass, A, which does.
Maybe you expect B's version of name to override A's? Variables don't get overridden. A is accessing the static variable name defined on A, that the method was originally called on B doesn't affect that.
Inheritance and static methods don't work well together. OO concepts like polymorphism rely on runtime dispatching, the word static should imply the opposite of that. With polymorphism the program works at a high level of abstraction, referring to the objects by a super type and letting the subclasses work out the details. With static methods you have to refer to the specific subclass you want the method called on, so you don't have that level of abstraction.
Welcome back to Java again.
You are using static variable in class A and B. These variables are associated with class instead of the objects.
If you change your method to get name from the User, it will work as you are expecting.
You need to override the method getName():
public class B extends A {
private static String name = "B";
private static String description = "This is B";
public B() {}
#Override
public static String getName() {
return name;
}
public B(User user) {
super(user);
}
}
The problem you are facing lies in the definition of the methods getName and getDescription: They are defined in class A as static members. This means that even when calling B.getName() the actual call is A.getName() and there the static member variable value of name is set to None.
When thinking about inheritance you have be careful what you declare as static. This has nothing to do with Interfaces or abstract classes.
public class A {
protected String name = "None";
protected String description = "No description";
public A() {}
public A(User user) {
user.setData(this);
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
}
public class B extends A {
public B() {
name = "B";
description = "This is B"
}
public B(User user) {
super(user);
}
}
public class User {
private A a;
public void setData(A a) {
this.a = a;
}
public A getData() {
return a;
}
}
With the protected keyword you can access the fields from the extending class.
See also:
http://www.javatpoint.com/static-keyword-in-java
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
A couple of things to note in your class :
name and description are static variables in both A and B
getName is a static method in A
static variables are bound to the class and static methods can't be overridden
This is the expected behavior since getName() method of class A has access to member variable of its own class that is "name" of class A. It is NOT because of name is static even if you make it non-static and you access it as shown in below code snippet it would return "None". Remember that only methods get overridden not member variables. So "name" of class B is not overriding "name" of class "A".
B b = new B();
System.out.println(b.getName()); --> "None" ("name" is non-static)
----------------------------------------------
System.out.println(B.getName()); --> "None" ("name" is static)
Also, if you want to get "B" as output , override getName() method of class A in class B and make method and variable non-static.

Java abstract class constructor and new keyword

I am a junior developer and I am familiar with the theory behind java abstract classes and how they can have constructors to force subclasses to set certain constructor parameters, and how abstract classes themselves cannot be instantiated. However, when looking at some refactored code in my company's test framework I am slightly puzzled.
This abstract class
public abstract class WaitForTestOutcomeThenAssert {
private long maxWait;
public WaitForTestOutcomeThenAssert(long maxWait) {
this.maxWait = maxWait;
}
public void waitForConditionThenAssert() {
...
...
}
protected abstract boolean checkCondition();
}
gets referenced in this class:
public class DbWrapper extends AbstractDB {
#Override
public void assertColumnValueNotNull(final String schema, final String table, final String columnName, final String whereClause) {
new WaitForTestOutcomeThenAssert(this.assertionTemporalTolerance) {
#Override
public boolean checkCondition() {
return getColumnValue(schema, table, columnName, whereClause) != null;
}
}.waitForConditionThenAssert();
}
}
Since we can't instantiate an abstract class, can someone please explain to me exactly what happens and what gets created when we use new keyword in front of an abstract class constructor?
Try looking at anonymous classes. Here you have an anonymous class declaration that extends abstract class WaitForTestOutcomeThenAssert and overrides checkCondition method.
This is not an abstract class
new WaitForTestOutcomeThenAssert(this.assertionTemporalTolerance) {
#Override
public boolean checkCondition() {
return getColumnValue(schema, table, columnName, whereClause) != null;
}
}
That is an anonymous class that extends WaitForTestOutcomeThenAssert. In other words, by writing that you are subclassing "WaitForTestOutcomeThenAssert" and instantiating it.
This is an Anonymous class. It's a shortcut to use Abstract class or Interface without having to explicitly write a subclass.

Usage of inner class

I can understand what inner class is and how to write program. My question is in what situation do programmers really need inner class?
Sometimes there is some functionality which is best represented as an object, but which is only meaningful within the context of another object, which does not necessarily need to be exposed to the outside world, and which can benefit from having access to the parent classes data (so as to not violate encapsulation).
The best example that I can think of is putting a Node class inside of a LinkedList. Nodes are only meaningful to the LinkedList, so they only exist within one. No one outside of the LinkedList cares about nodes or should have access to them.
An inner class allows us to remove that logic and place it into its own class. So from an object-oriented point of view, we've taken functionality out of where it doesn't belong and have put it into its own class.
Please go through this link....
http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html
Also as you know in Java exists nested classes, which is static inner clasess.
From previous posts becomes clear when we need to use an inner class but I think you also interested in the question "Why we need nested classes (static inner class)".
The answer is simply, there is the same purpose as for the inner class except few things.
1) The nested class (static inner) is required when we whant to exclude some logic that concerns another object but this logic might be used in outworld.
The simpliest examples is a builders or editors of some object. For example we have class Foo
which may have a lot of optional fields, to construct such object we may decide to introduce a builder class which will do this work.
public class Foo {
private int param1;
private int param2;
private int param3;
private Foo(FooBuilder builder) {
this.param1 = builder.param1;
this.param2 = builder.param2;
this.param3 = builder.param3;
}
public int getParam1() {
return param1;
}
public void setParam1(int param1) {
this.param1 = param1;
}
public int getParam2() {
return param2;
}
public void setParam2(int param2) {
this.param2 = param2;
}
public int getParam3() {
return param3;
}
public void setParam3(int param3) {
this.param3 = param3;
}
public static class FooBuilder {
private int param1;
private int param2;
private int param3;
public FooBuilder() {
}
public FooBuilder withParameter1(int param1) {
this.param1 = param1;
return this;
}
public FooBuilder withParameter2(int param2) {
this.param2 = param2;
return this;
}
public FooBuilder withParameter3(int param3) {
this.param3 = param3;
return this;
}
public Foo build() {
return new Foo(this);
}
}
}
This example illustrates at leas one reason why we need such classes
2) The second difference between inner and static inner classes is that the first one always has pointer to the parent class. Actully compiler creates synthetic field member for the non static inner class of the type of it's parent, exectly of this reason we can access private members of the parent class. The static inner clasess doesn't has such generated field member. For instance we has just simple parent class with declared non static inner class:
public class Foo {
public class FooBuilder {
}
}
but in fact if take into account the byte code it looks like:
public class Foo {
public class FooBuilder {
private Foo generatedNameHere;
}
}
if you want you can figure out this throught generated byte code.
One of the use of inner class is :
Inner class helps in multiple-inheritance. Inner class allows you to inherit from more than one non-interface.
//first case; can implement if two classes are interface
interface A { }
interface B { }
class X implements A, B { }
//second case; you can extend only one class. This case inner class can help to inherit other class as well
class D { }
abstract class E { }
class Z extends D {
void method() {
return new E() { }; //Anonymous inner class
}
}
When you want to specify a class that has sence only in context with the bounded one.
For example you write a MathOperations class that can execute four operations. So the operations can be represented as inner enum MathOps.
When the inner class is not used anywhere except the inbounded one.
You use anonymous inner classes to specify only the operation, for exmple if you want to sort a collection, you specify a Comparable class just for one method compare.
Collections.sort(employments, new Comparator<Employment>() {
#Override
public int compare(Employment o1, Employment o2) {
return o1.getStartDate().before(o2.getStartDate()) ? 1 : -1 ;
}
});
With inner classes you can access private members of the enclosing class.
They are useful for interface implementations that are only used by the enclosing class (event handlers in a application).
They are useful for providing fine grained access and creation control over an interface implementation that is retrieved externally (maybe something like an Iterator implementation).

Categories