instantiation of objects of other classes in java [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have this situation:
public class Number {
int num;
private TakeNumber take = null;
public Number() {
num = 5;
}
public void print() {
take.doSomething();
}
public int getNumber() {
return num;
}
public static void main(String[] args) {
new Number();
}
}
public class TakeNumber {
private Number number = new Number();
public void doSomething() {
System.out.println(number.getNumber());
}
}
Now, can someone explain me these situations:
I want to know what the compiler interprets here : private Number number = new Number();
Initialize the object in question and passing the required methods
Is correct initialize one object to null and then call a function on that object, as shown
in brief
I would like to know if you can call a method of a class of another class:
without the required function to be static
IMPORTANT do not inherit the classes because I want to use methods of these classes, for example:
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato

I would like to know if you can call a method of a class of another class:
without the required function to be static
If the methods are not static, then you will need an instance of that object to call it.
Object o = new Object();
o.doSomething();
Is how you access an instance method.
I have classes that are conceptually different as Tomato and machine, I would call the methods of Machine into Tomato
This is fine. This is called composition. Composition is a has a relationship between classes. A class Man has a class Car, but Is a class Person. And it is perfectly valid to write code as you have shown. This is how you use composition to expose only the interface of a composite object that you want. For example..
public class MyClass extends MyOtherClass
Now you've just exposed the whole interface of MyOtherClass. This might not be desired.
public class MyClass {
MyOtherClass otherClass;
public void doSomething() {
otherClass.doSomething();
}
}
Now, you've only exposed the doSomething() method. This is useful when, as you said, your objects are conceptually different, but require some shared functionality. It is a perfectly valid code practise.
NOTE: Given the confusing nature of your question, I imagine I've missed some stuff out so please comment with desired edits.

Related

Questions about constructing a child class that extends an abstract class constructor without super() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I am new to Java OOP and have been studying about this reading a GitBook called AP Computer Science in Java
I found this page very confusing:https://codehs.gitbooks.io/apjava/content/Classes-And-Object-Oriented-Programming/class-design-and-abstract-classes.html
the code is like this
public abstract class VehicleClass {
private String type;
private String vehicleName;
public VehicleClass(String vType, String vName) {
type = vType;
vehicleName = vName;
}
/* This will need to be abstract, since
* we will need to implement different formulas
* depending on if the vehicle is electric or
* gas powered.
*/
public abstract double getMileage();
}
/* As you can see, in both classes, we have `getMileage` implemented
* with different formulas.
*/
public class Truck extends VehicleClass {
private double gasTankCapacity;
private double milesPerTank;
public Truck(double capacity, double miles) {
gasTankCapacity = capacity;
milesPerTank = miles;
}
public double getMileage() {
return milesPerTank/gasTankCapacity;
}
}
public class ElectricCar extends VehicleClass {
private double maxCharge;
private double milesPerCharge;
private double maxEnergyUsage;
public ElectricCar(double charge, double maxEnergy, double milesCharge) {
maxCharge = charge;
maxEnergyUsage = maxEnergy;
milesPerCharge = milesCharge;
}
public double getMileage() {
return (maxCharge*milesPerCharge)/maxEnergyUsage;
}
}
MY questions are:
1. Why does he build the constructor of the two child classes without using super(). Doesn't he need to pass type and vehicleName to the super-class's constructor?
2. Why does he make type and vehicleName in the super-class to be private? I know that child class cannot inherit instances variables from the super class. Why doesn't he use protect instead?
You are totally right! That code will not compile.
It's hard to say without knowing the purpose of those variables and of the class.
You're right, and it doesn't compile for that reason.
You may only omit parameterless calls to super, if there is such a constructor in the super class, in which case it is automatically inferred.
Speculation about the reason: The author wanted to show something else (as stated in the comments), maybe first had a working solution but then decided, that the vtype code bloated the example too much up and removed it, without testing again.
To Q.2, why does he make type and vehicleName in the superclass to be private?
I would say, you inherit instance variables, private or not, you just don't have direct access to them.
Why doesn't he use protect instead?
We can't tell. Since it is only demo code, and the private members aren't used and not accessible via getter or setter, we just can't tell. Maybe it is an example which is later extended and then they get used?

could one day the JVM "void return type only" become a self call chaining new capability? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
could one day the JVM "void return type only" become a self call chaining new capability?
1) this would be about allowing anything to be returned: but may be not so good, as the commenters say
If not, why? why it is a good reason to never allow that below?
class A{
// public Object a(){return null;}
public void a(){}
}
class B extends A{
#Override
public String a(){return "";}; //error
}
2) this is about self call chaining, restricted usage, would be much better/safer/clearer option
Why I want that? to let setters be chain linked like: new B().set1(1).set2(2).set3(3); using getThis() trick
void return is so useless, it would break nothing because it is already ignored by everything!
As we wont have access to most setters of libraries, and dont want to fork them all, the real deal would be to let void (or Void?) become Object I guess. Or even better, become a new restricted type called "? extends Self" letting the getThis() trick be part of the JVM core.. So this would be a restricted use case, only alowing self chaining calls.
Why a high level language (then assembler) cant allow this covariance "law breaking" capability/option? If we call a method that returns something and ignore/do not capture it, it will work equivalently to a void return!
So the otherwise back functionality could be allowed bringing new light to where once there was nothing but a desert of options.
So, this is the real deal, where a setter returning void would leave us no options:
class A<SELF extends A>{
// public void set(){} //this one leaves us no options
public SELF set(){return getThis();}
public SELF getThis(){return (SELF)this;}
}
class B extends A<B>{
#Override public B set(){return getThis();}
#Override public B getThis(){return this;}
}
Basically, I am not looking for an opinion, I am looking for a good reason/explanation.
so, I understand I am further argumenting beyond the requests of this question: Why is void not covariant in Java?
Java does support covariant return types. For instance:
class A {
Object run() { ... }
}
class B {
String run() {...}
}
As such, your chained setters example is possible using overriding (or generics). But the resulting code might not feel like idiomatic Java.
Because of the basic laws of inheritance. Specifically, the Liskov substitution principle in SOLID:
https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”
By changing the return type, the subclass would not follow this principle. Calling b.a() would not return void, but a String instead.
I can't think of any specific problems in the specific case of methods that return void and later get overridden to return something else, but that's such an odd case that I'd be concerned that people would abuse it and my Class D that extends A returns an int on D.a() and now everyone's confused.
Because when I tell my fellow programmers that I'm calling method a() of some subclass of A, they know what it's going to return.
class A{
// public Object a(){return null;}
public void a(){}
}
class B extends A{
#Override
public String a(){return "";}; //error
}
class C extends A{
#Override
public int a(){return 0;}; //error
}
Now what does method a() do? How do I communicate with my team in a sensible manner about this method?
Now imagine I have this:
List<A> listOfAs = new ArrayList<>();
What happens when I call listOfAs.get(0).a() / 2?

Why should I create function Add? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Most of expert programmer here have down voted my answer as bad answer
How to add a field to an ArrayList from a different class?
So, I wonder why do I need to create another function Add to add items to my list. While most of programming language such as Java C# and VB.NET allow us a very simple way by using Getter as a List or ArrayList that we be able to add and use many function that this class has directly as sample as bellow
C#
class Program
{
static void Main(string[] args)
{
Employee emp = new Employee();
emp.lst.Add("Hello");
}
}
class Employee
{
private List<string> _lst = new List<string>();
public List<string> lst
{
get { return _lst; }
}
//public void add(String item) {
// _lst.Add(item);
//}
}
Java
public class MainApp {
public static void main(String[] args){
Employee emp = new Employee();
emp.getLst().add("My String");
}
}
class Employee{
private List<String> lst = new ArrayList<String>();
public List<String> getLst() {
return lst;
}
public void setLst(List<String> lst) {
this.lst = lst;
}
}
Most of languages are allow us to do this ways. So, what is the reason I need to create function Add for on Employee?
Practical reason: getList() may return either internal list or copy of that list. There is no way for consumer of the class to know what is the behavior of the method without knowing implementation of getList() (or less likely find and read documentation on that particular method of particular class). So adding to or modifying result of getList() call in any other way may never change the original object and proving correctness will require reading all the code including (frequently private) implementation of getList().
Whether it is useful to expose separate methods to add to the list or not is personal choice based on particular code. Generally it is better to provide specific methods for all operations on the object as one can guarantee consistency of the state of the object.
For example if object is plain data transfer object having raw lists is fine there, but if it is Student exposing modifiable list of classes may easily lead to inconsistent state if for example total score class is stored independently.

Best factory implementation [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
So because I'm currently reading into design patters I have a "newbie" and at least for me interesting question to ask.
What Factory implementation is the best? I've seen factories where the create method is hardcoded and if a new subtype is added I'll need to edit the method. For example:
public class ProductFactory{
public Product createProduct(String ProductID){
if (id==ID1)
return new OneProduct();
if (id==ID2) return
return new AnotherProduct();
... // so on for the other Ids
return null; //if the id doesn't have any of the expected values
}
...
}
This seems to be the implementation that takes the lowest amount of resources. But furthemore I've seen implementations that use reflection:
class ProductFactory
{
private HashMap<String, Class> m_RegisteredProducts = new HashMap<>();
public void registerProduct (String productID, Class productClass)
{
m_RegisteredProducts.put(productID, productClass);
}
public Product createProduct(String productID)
{
Class productClass = (Class)m_RegisteredProducts.get(productID);
Constructor productConstructor = cClass.getDeclaredConstructor(new Class[] { String.class });
return (Product)productConstructor.newInstance(new Object[] { });
}
}
Which seems to be the slowest one because it is using reflection to work. And the last implementation seems to take the most RAM because it has an extra instance of a specific class stored.
class ProductFactory
{
private HashMap<String, Product> m_RegisteredProducts = new HashMap<>();
public void registerProduct(String productID, Product p) {
m_RegisteredProducts.put(productID, p);
}
public Product createProduct(String productID){
((Product)m_RegisteredProducts.get(productID)).createProduct();
}
}
Product classes for the last factory:
abstract class Product
{
public abstract Product createProduct();
...
}
class OneProduct extends Product
{
...
static
{
ProductFactory.instance().registerProduct("ID1", new OneProduct());
}
public OneProduct createProduct()
{
return new OneProduct();
}
...
}
Both the second last and last implementation allow to register new products without modifying the factory class in for example a static block in the to be registered product extending/implementing class. Is this better? And if so, which of those two implementation is the better one? Or is the hard coded implementation better because it seems to require less resources.
Approach 1) Parametrized Factory implementation. Overtime we create a new Product object we have to modify the Factory.
Approach 2) We dont need to modify the Factory in order to add a new implementation. In addition the factory needs to know in advance all the available classes in order to begin instantiating them. Performance is not a factor here because on a modern JVM the performance loss from reflection will be negligible.
Approach 3)If I understand correctly the Product is exposing a factory method. Each implementation of Product through Polymorphism is responsible for providing logic for instance creation. Although I dont get it how you will use exactly a non static method. And if you use static you loose your Polymorphism. Approach 3 is not very clear to me. Is the Product actually a Wrapper around the real Product ?
Approach number 1 is least flexible

why java does not support dynamic variable dispatch [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Please excuse me if title is wrong. There are two class Test and TestChild1 where TestChild1 is inherited from Test. Both classes have a variable named "a". When I tried to access variable "a" through superclass variable which is instantiated with subclass object, it is giving the value that is initialized with in superclass not subclass.
following is the code that raised the doubt
class Test {
public int a = 10;
}
class TestChild1 extends Test {
public int a = 20;
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.a); // results in 10
}
}
Please give me the reasons for this behavior. Thanks in advance....
Because the Java designers decided to make methods polymorphic (and thus overridable), but not fields.
When you reference a field from an object, the compiler decides which field to use, based on the declared type of the variable, which, in this case, is Test.
When you refer to methods, the JVM, at runtime, chooses which method to call based on the actual, concrete type of the object which, in this case, is TestChild.
OO is all about encapsulation of state, so you should almost never expose fields to the outside anyway.
The class TestChild1 has two variables with the same name. If you access them through Test you get the first one, from TestChild1 you get the second one.
To get your expected result, you should not declare a in the derived class. Instead you should initialize it in the costructor of the derived class.
You declared your object as Test, not the subclass. At compile time that means you refer to the base class which has 10.
Because behavior is associated with methods and not with fields.
So, fields have static binding (in this case this, since test is of type Test, value of a is assigned with value 10). Whereas methods have dynamic binding.
Since, the variable a doesn't define the behavior of Test class, it is assigned the value as per its type and not as per its instance.
JB Nizet have already said everything, but I will add this code for more understanding:
class Test {
private int a = 10;
public int getA() {
return a;
}
}
class TestChild1 extends Test {
private int a = 20;
public int getA() {
return a;
}
}
class Main {
public static void main(String args[]) {
Test test = new TestChild1();
System.out.println(test.getA()); // results in 20
}
}
So if you would encapsulate your fields, you would have expected behaviour.

Categories

Resources