i created two classes, each one is in a different package ... here is the class inside the main package:
package Main;
public class Main {
Public static void main(String [] args ) { .....}
}
// class in main package
class ClassS{
public int publicAtttibute;
private int pricatdAttribute;
And this is the second class in another package:
package second;
public class ClassC{
public static void doSomething(){
ClassD ref = new ClassD();
} }
But i’m not sure if this code makes the classD and it’s attributes visible to class c, can someone please clarify it
You defined an instance object of classD inside the classC which means that ClassD and all of it’s public attributes would NOT be visible to ClassC ..... if you want the ClassD to visibile but the attributes aren’t you could code it like this:
package other:
public class ClassC{
public static void visible(){
ClassD ref = new ClassD();
ref.publicAttribute = 3;
ref.privateAttribute=3;
}}
Related
Okay so this has been an issue I keep running across. Now there are plenty of ways to do this, but I am wondering what you consider to be 'best practice'
Suppose we have project structure as follows:
Java Project:
src/
PackageA/
ClassA.java
PackageB/
ClassB.java
ClassC.java
Main.java
Each class is as follows:
public class Main {
private ClassA classA;
private ClassB classB;
public Main(){
}
public void runMainMethod(){
//Init Objects
classA = new ClassA();
classB = new ClassB();
classA.getDataFromClassC();
}
}
public class ClassA {
public ClassA(){
}
public void getDataFromClassC(){
//Best way to get Data from classC?
}
}
public class ClassB {
private ClassC classC;
public ClassB(){
loadClassC();
}
private void loadClassC(){
classC = new ClassC("ExampleName");
}
}
public class ClassC {
private String name;
public ClassC(String name){
this.name = name;
}
public String getNam(){
return name;
}
}
I feel like passing Main through each class and creating a getter method in Main (for classB), and then another getter Method in B (for classC) is overkill.
Especially if it goes deeper. What if class C holds an object Class D? And I wanted to access class D from Class A?
Maybe I am not performing the best practice for OOP?
Any information on how you handle this, or a better practice would be greatly appreciated!
Question2:
What if, you only want one ClassB (Maybe because ClassC was loaded from a file, and multiple ClassB's will not be syncronized in respect to the class C).
Ex I want to avoid this issue:
ClassC classC = new ClassB().getClassC();
ClassC2 classC2 = new Class().getClassC();
classC.setName("C");
classC2.setName("C2);
where both classes have different name values
I have the below two classes. I'm wondering how I'm able to call the instance method of ClassA i.e. AMessage() in class B with out the instance of a ClassA or ClassB created?
I was thinking I should call instance method of ClassA i.e. AMessage() in class B as below:
new ClassA().AMessage(); //no compile error
new ClassB().Amessage(); //no compile error
Parent Class (ClassA.java)
public class ClassA {
public void AMessage(){
System.out.println("A Message");
}
}
Child Class (ClassB.java)
public class ClassB extends ClassA{
public void BMessage(){
AMessage(); //no compile error
}
public static void main(String[] args){
new ClassB().BMessage();
}
}
When a class extends another class, it automatically inherits the visible fields and methods of the base class. By visible I mean accessible members. Private members are not inherited. Learn more about inheritance in http://www.tutorialspoint.com/java/java_inheritance.htm
So if you have a class ClassA having a method AMessage like this :
public class ClassA{
public void AMessage(){
System.out.println("A message");
}
}
and ClassB which extends ClassA like this :
public class ClassB extends ClassA{
public void BMessage(){
AMessage();
}
public static void main(String[] args){
new ClassB().BMessage();
}
}
ClassB automatically inherits members of ClassA i.e. they act as if they are members of ClassB itself. That's why we can call the instance method of ClassA inside ClassB without any instance, because they belong to ClassB as well. Also besides instance methods, you can call static methods like that as well. (But of course you can not call instance methods inside static methods.)
As an additional answer I would like to suggest that (although it is not related to the question but it is a good practice) you should not name any method of a class (instance or static) starting with a capital letter. It doesn't generate any compiler error if you still name it like that, but it affects the readability. I have written the names like that only to relate to your question.
Use super keyword to call base class methods. Check this for reference -
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
public class ChildClass extends BaseClass{
public static void main(String[] args){
ChildClass obj = new ChildClass();
obj.Message();
}
public void Message(){
super.Message();
}
}
class BaseClass {
public void Message(){
System.out.println("Base Class called");
}
}
Or you can do it like this as well -
public class ChildClass extends BaseClass{
public static void main(String[] args){
new ChildClass().Message();
}
}
class BaseClass {
public void Message(){
System.out.println("Base Class called");
}
}
yes you can call method directly instance method of parent class from child class object provided parent class method should be public
you can call in this way
new ClassB().AMessage();
it will also work
if i have a pacakage access class somthing like this:
package AA;
class A {
// ...
}
which is only accessed by classes on package AA. What is the difference between declaring on this class a methods as a protected or public?
Isn't it is the same because the class only accessed from its pacakge ?
Package AA might have a public class B that extends A.
In that case, a class C from a different package may create an instance of B and call any public methods of A for that instance.
If, however, you define methods of A as protected, C would have to be a sub-class of B in order to call those methods.
package AA;
class A
{
public void foo() {}
protected void bar() {}
}
package AA;
public class B extends A
{
}
package BB;
public class C extends B
{
public void func ()
{
super.bar (); // OK, since bar is protected and C extends B
// which extends A
}
public static void main (String[] args)
{
B b = new B();
b.foo(); // OK, since foo is public
b.bar(); // doesn't compile, since bar is protected
}
}
It makes difference when using reflection, like Class.getMethods()
I would like to make an object of a class A and it is initialized in class B, class C, and class D
This object should be shared; that is if any changes made to objA in these classes(C and D), its content remains the same even after objC,'objD' are destroyed, supposely that class B is the main class. I would like to use its property is class B
class A {}
class B
{
initialize class A object and use-change its property
initialize class C object and use-change its property
initialize class D object and use-change its property
}
class C{initialize class A object and use-change its property}
class D{initialize class A object and use-change its property}
class X{initialize B and destroy objC,objD, from objB use property of objA of class B}
A non static attempt would look like this:
Your target object:
public class A {
}
Your classes, that do something with the object:
public class C {
private final A a;
public C(final A a) {
this.a = a;
}
public foo() {
// do something with a
}
}
public class D {
private final A a;
public D(final A a) {
this.a = a;
}
public otherFoo() {
// do something with a
}
}
Your main class:
public class B {
public static void main(String[] args) {
final A a = new A();
final C c = new C(a);
final D d = new D(a);
c.foo();
d.otherFoo();
}
}
Try making the object static that way any changes made to one instance of that object will be consistent across all objects that use that object that are in the same thread.
This is essentially a singleton pattern, you can pass your class around or get it from the main. I prefer the latter personally, like so:
public class YourMain {
private final ClassA clazzA;
private final ClassB clazzB;
private final ClassC clazzC;
private final ClassD clazzD;
public YourMain() {
this.clazzA = new ClassA();
this.clazzB = new ClassB(this);
this.clazzC = new ClassC(this);
this.clazzD = new ClassD(this);
this.clazzB.doSomething();
}
public ClassA getClassA() {
return this.clazzA;
}
}
From there, you can chain back up to your main class in the other classes:
public class ClassB {
private final YourMain project;
public ClassB(YourMain project) {
this.project = project;
}
public void doSomething() {
this.project.getClassA().someMethod();
}
}
Of course, this isn't 100% what you would implement it like (you need to mind the order you load things in if you are passing your main class instance), but for something like this I usually find it is the cleanest and provides the easiest availability to all my classes across a project.
Let's say I have 3 classes
class1, class2 and class3.
How can I have it that class1 can only get instantiated by class2 (class1 object = new class1()) but not by class3 or any other class?
I think it should work with modifiers but I am not sure.
I want to rename your classes to Friend, Shy and Stranger. The Friend should be able to create Shy, but Stranger should not be able to.
This code will compile:
package com.sandbox;
public class Friend {
public void createShy() {
Shy shy = new Shy();
}
private static class Shy {
}
}
But this code won't:
package com.sandbox;
public class Stranger {
public void createShy() {
Friend.Shy shy = new Friend.Shy();
}
}
In addition, if we create a new class called FriendsChild, this won't compile either:
package com.sandbox;
public class FriendsChild extends Friend {
public void childCreateShy() {
Shy shy = new Shy();
}
}
And this naming convention makes sense when you think about it. Just because I'm a friend of someone doesn't mean my child knows them.
Notice that all these classes are in the same package. As far as I can understand, this is the scenario you're looking for.
Another option besides making the constructor protected:
Make the class1 constructer private
Make a public static factory method that requires a valid instance of class2 inorder to return an instance of class1
Make class1 inner class of class2.
Update
make protected constructor and put the eligible class in same package, if you want any class outside of package to construct this instance then you need that class to extend ClassA in this example,
if you restrict it then go for default access specifier
package com.somthing.a;
public class ClassA {
ClassA() {
super();
// TODO Auto-generated constructor stub
}
}
package com.something.a;
public class ClassB {
public static void main(String[] args) {
new ClassA();//valid
}
}
package com.something.c;
public class ClassC {
public static void main(String[] args) {
new ClassA();// invalid
}
}