标签:string style class print 问题 blog void this display
class Father{
public int num1=10;
private int num2=20;
protected int num3=30;
public Father(int num1,int num2,int num3){
this.num1=num1;
this.num2=num2;
this.num3=num3;
}
public Father(){
System.out.println("Father");
}
@Override
public String toString() {
return String.format("%d %d %d",num1,num2,num3);
}
}
class Son extends Father{
public Son(int num1,int num2,int num3){
super(num1,num2,num3);
}
@Override
public String toString() {
return super.toString();
}
public static void main(String[] args){
System.out.println(new Son(1,2,3));
}
}//输出 1 2 3
a.创建子类对象的时候会调用父类的构造函数,如果是无参数的构造函数,会自动的调用,不用写super()
b.Father father=new Son();//Son的实例但是进行了向上转型,father引用可以调用Father类中的函数,以及子类中被重写的函数(多态),但是父类的引用是不能调用子类的属性的,因为多态只针对方法不针对属性
例子:
public class Main {
public static void main(String[] args){
/*创建子类对象的时候会调用子类的构造函数*/
Son son=new Son();
/*输出num1的值*/
Father father=new Son();
System.out.println(father.num1);
/*调用函数f()*/
father.f();
}
}
class Father{
public int num1=10;
public Father(){
System.out.println("Constructor of Father");
}
public void f(){
System.out.println("Father‘s f()");
}
}
class Son extends Father{
public int num1=20;
public Son(){
System.out.println("Constructor of Son");
}
@Override
public void f(){
System.out.println("Son‘s f()");
}
}//输出:
Constructor of Father
Constructor of Son
Constructor of Father
Constructor of Son
10
Son‘s f()
class A{
public String name=new String(“Tom”);
protected String school=new String(“SouthEast University”);
private String sex=new String(“M”);
}
public class Test{
public static void main(String[] args){
Object obj=new Object();
System.out.println(obj.hashCode());
}
}
//解释
按道理所有的类都是Object的子类,hahCode是protected函数,也就是说对于Object的子类,都可以执行hashCode()函数,但是必须在子类包中,这里就是Object所在的包中
这样写就是没问题的
@Override
public int hashCode(){
return super.hashCode();
}
作用如下
class Instrument {
private void display(){System.out.println("Instrument‘s display");}//无法被覆盖
}
public class Wind extends Instrument{
private void display(){System.out.println("Wind‘s display");}//并不是覆盖父类的函数,而是添加自己的函数
public static void main(String[] args){
Instrument instrument=new Wind();//向上转型为父类的对象同时丢失父类的private方法
instrument.display();//Wrong
}
}
标签:string style class print 问题 blog void this display
原文地址:http://www.cnblogs.com/yangyunnb/p/6090359.html